Difference between instance attributes and class attributes

做~自己de王妃 提交于 2019-12-11 15:12:28

问题


I'm trying to learn about the instance and class attributes in python. Then am a little confused: is this_obj.var an instance attribute or it belongs to the class attribute. The code is below

class Myclass (object):
    var = 10

this_obj = Myclass() 
this_obj.somevar = 12
that_obj = Myclass()
that_obj.somevar = 12

回答1:


Instance and class attributes can be kind of confusing to understand at first. The best way of thinking about it is to pay attention to the name.

Instance attributes are owned by the specific instance of the class, meaning that these attributes can vary from instance to instance of a specific class.

On the other hand, Class attributes are owned by the class itself, so the attribute has the same value for each instance of a particular class.

In your example, var would be a class attribute to every instance of MyClass. However, once var is set to a different value for any given instance, say this_obj.var = 69, then this_obj.var is now an instance attribute to the this_obj instance. Meaning, instance attribute are created upon changing the class attribute of any instance.

Hope that helps!

EDIT: You can also change the class attribute value itself, meaning it'll change for all instances without an instance attribute for that specific variable. For example MyClass.var = 34 would change the value for all instances of MyClass that hasn't created an instance attribute yet.



来源:https://stackoverflow.com/questions/47070899/difference-between-instance-attributes-and-class-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!