Python class attributes and their initialization

前端 未结 3 580
陌清茗
陌清茗 2021-01-12 21:08

I\'m quite new in python and during these days I\'m exploring classes. I have a question concerning attributes and variables inside classes: What is the difference between d

3条回答
  •  感情败类
    2021-01-12 21:54

    q=1 inside the class is a class attribute, associated with the class as a whole and not any particular instance of the class. It is most clearly accessed using the class itself: MyClass1.q.

    A instance attribute is assigned directly to an instance of a class, usually in __init__ by assigning to self (such as with self.p = p), but you can assign attributes to an instance at any time.

    Class attributes can be read either using the class binding (MyClass.q) or an instance binding (my.q, assuming it is not shadowed by an instance attribute with the same name). They can only be set, however, using a class binding. Setting a value with an instance binding always modifies an instance attribute, creating it if necessary. Consider this example:

    >>> a = MyClass1()
    >>> a.q
    1
    >>> a.q = 3    # Create an instance attribute that shadows the class attribute
    3
    >>> MyClass1.q
    1
    >>> b = MyClass1()
    >>> b.q   # b doesn't have an instance attribute q, so access the class's
    1
    

提交回复
热议问题