python: What happens when class attribute, instance attribute, and method all have the same name?

前端 未结 4 1197
难免孤独
难免孤独 2020-12-02 19:02

How does python differentiate a class attribute, instance attribute, and method when the names are the same?

class Exam(object):

    test = \"class var\"

          


        
4条回答
  •  孤城傲影
    2020-12-02 19:13

    How to call
    class attribute, Exam.test

    You can't because when executing def test(self) the name testis bound to the method in the class and the reference to "class var" is lost.

    instance attribute test_o.test --> "Fine"

    You already did that.

    method test_o.test()

    You can't call it that way because when executing self.test = n the name test is bound to whatever object n references in the instance and the reference to the method in the instance is lost.

    But as pointed in other answers you can call the method in the class and pass the instance to it: Exam.test(test_o)

提交回复
热议问题