实例属性和类属性之间的区别 [英] Difference between instance attributes and class attributes

查看:316
本文介绍了实例属性和类属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解python中的实例和类属性.然后有点困惑:this_obj.var是实例属性还是它属于类属性.代码在下面

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

推荐答案

实例和类属性乍一看可能会让人感到困惑. 最好的考虑方法是注意名称.

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.

在您的示例中,var将是MyClass的每个实例的类属性.但是,一旦将任何给定实例的var设置为不同的值,例如this_obj.var = 69,则this_obj.var现在是this_obj实例的实例属性.意思是,实例属性是在更改任何实例的类属性时创建的.

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.

希望有帮助!

您还可以更改类属性值本身,这意味着它将为所有实例更改,而没有该特定变量的实例属性.例如,MyClass.var = 34将更改尚未创建实例属性的所有MyClass实例的值.

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.

这篇关于实例属性和类属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆