Python类属性及其初始化 [英] Python class attributes and their initialization
问题描述
我在Python和在这些日子里,我探索类是新的。我有关于内部类属性和变量的问题:什么是通过刚 Q = 1
在类的主体定义属性之间,并通过定义<$ C $的区别C> self.q = 1 的 __ __的init
里面呢?例如,是以下两种可能性之间的区别?
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 defining an attribute via just q=1
in the body of the class and via defining self.q=1
inside the __init__
? For example, what is the difference between the following two possibilities?
class MyClass1:
q=1
def __init__(self,p):
self.p=p
def AddSomething(self,x):
self.q = self.q+x
和
class MyClass2:
def __init__(self,p):
self.q=1
self.p=p
def AddSomething(self,x):
self.q = self.q+x
对于示例的输出:
The output of for example:
>>> my=MyClass1(2)
>>> my.p
2
>>> my.q
1
>>> my.AddSomething(7)
>>> my.q
8
不取决于是否 MyClass1的
或 MyClass2
被使用。无论是在 MyClass1的
也不 MyClass2
并发生一个错误。
does not depend on whether MyClass1
or MyClass2
is used. Neither in MyClass1
nor in MyClass2
does an error occur.
推荐答案
Q = 1
里面的类是类属性,用类作为一个整体,而不是相关的类的任何特定实例。它使用的是类本身最清楚访问: MyClass1.q
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
.
一个实例属性是直接在 __通过分配到
如用自
(分配到一个类的实例,一般的init __ self.p = p
),但你可以在任何时间分配属性的实例。
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.
类属性可以的阅读的无论是使用类绑定( MyClass.q
)或实例结合(我的.Q
,假设它不是由一个实例阴影具有相同名称的属性)。他们只能的设置的,但是使用一类具有约束力。设定值与实例绑定的总是的修改实例属性,创建它,如果必要的。考虑这个例子:
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
这篇关于Python类属性及其初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!