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

前端 未结 4 1194
难免孤独
难免孤独 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

    You can write

    Exam.test(test_o)
    

    or

    Exam.test.__get__(test_o)()
    

    In the latter case you're using the fact that methods are descriptors to convert the to a bound method, so you can call it with single brackets.

    When you write test_o.test(), Python doesn't know that you're trying to call a method; you might be trying to call a function or callable object that has been installed on the object as an instance data member. Instead it looks up the attribute test, first on the object and then on its class, but since the attribute exists on the object it hides the method on the class.

    The class member

    test = "class var"
    

    is not accessible (in fact it doesn't exist anywhere), because it is overwritten by the method test; when a class statement is executed, its namespace is collected into a dict before being passed to its metaclass, and later names override earlier ones.

提交回复
热议问题