【问题标题】:regarding proper use of __init__ in Python [duplicate]关于在 Python 中正确使用 __init__ [重复]
【发布时间】:2015-10-15 14:32:08
【问题描述】:
这两个语句在 Python 中的语义差异是什么?
class Person :
age = 5
和
class Person :
def __init__(self):
self.age = 5
如果我在这两种情况下都实例化一个对象,例如
mario = Person ()
在这两种情况下,mario 的 age 都是 5
那么,如果一个对象一被实例化就被分配了一个属性,即使不使用__init__,在哪里需要使用__init__方法呢?
【问题讨论】:
标签:
python
class
object
init
【解决方案1】:
__init__ 属性是指类实例的变量,在类下面表示它是一个类变量。
例如,当您使用变量列表时,这将很重要:在类的正下方将使列表在类之间共享实例,即,如果您在类的一个实例中附加到该列表,该类的所有其他实例也将“看到”列表中的附加项。
class Foo:
x = []
a = Foo()
b = Foo()
a.x.append(1)
b.x == [1] # True
c = Foo() # Even being created after 1 has been appended, still:
c.x == [1] # True
当您使用__init__ 时,情况并非如此,“x”属性对于每个实例化都是唯一的。
【解决方案2】:
两者的区别在于,在上面的例子中你创建了一个类属性,而在 init 中你创建了一个实例属性。两者的区别是这样的:
class Foo():
bob = "my name is bob"
print(Foo.bob)
# outputs "my name is bob"
class Foo():
def __init__(self):
self.bob = "my name is bob"
在做print(Foo.bob):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute 'bob'
要在 init 中访问 bob,您必须实例化:
f = Foo()
print(f.bob)
# outputs "my name is bob"
这两种实现的进一步区别在于类属性将在所有实例之间共享,而实例属性仅在您的实例内共享。
因此,对于在您的__init__ 中定义的任何内容,如果您创建一个新的 Foo 对象,您将不会将您可能对 init 中的变量所做的任何更改带到 Foo 的其他实例。
但是,对于类属性,您更改的任何类属性都将在 Foo 的所有实例中更改。