自我定义的有用性?

2024-04-25 05:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

是的,看看这个:

class A(object):
    def __init__(self):
        self.lst = []

class B(object):
    lst = []

现在试试:

>>> x = B()
>>> y = B()
>>> x.lst.append(1)
>>> y.lst.append(2)
>>> x.lst
[1, 2]
>>> x.lst is y.lst
True

而这个:

>>> x = A()
>>> y = A()
>>> x.lst.append(1)
>>> y.lst.append(2)
>>> x.lst
[1]
>>> x.lst is y.lst
False

Does this mean that x in class B is established before instantiation?

是的,它是一个类属性(在实例之间共享)。在类中,它是一个实例属性。只是碰巧字符串是不可变的,因此在您的场景中没有真正的区别(除了类B使用更少的内存,因为它只为所有实例定义一个字符串)。但在我的例子中有一个很大的例子。

正如其他人所说,这是类上的变量和类实例上的变量之间的区别。请参见以下示例。

>>> class A:
...     a = []
... 
>>> class B:
...     def __init__(self):
...         self.b = []
... 
>>> a1 = A()
>>> a1.a.append('hello')
>>> a2 = A()
>>> a2.a
['hello']
>>> b1 = B()
>>> b1.b.append('goodbye')
>>> b2 = B()
>>> b2.b
[]

对于元组、字符串等不可变对象,很难注意到差异,但对于不可变对象,它会更改所有的-应用的更改在该类的所有实例之间共享。

还要注意,关键字参数默认值也会发生同样的行为!

>>> class A:
...     def __init__(self, a=[]):
...         a.append('hello')
...         print(a)
... 
>>> A()
['hello']
>>> A()
['hello', 'hello']
>>> A()
['hello', 'hello', 'hello']

>>> class B:
...     def __init__(self, b=None):
...         if b is None:
...             b = []
...         b.append('goodbye')
...         print(b)
... 
>>> B()
['goodbye']
>>> B()
['goodbye']
>>> B()
['goodbye']

这种行为困扰了许多新的Python程序员。很高兴你能早点发现这些区别!

在第一个示例中,有类实例的变量。此变量只能通过实例(自选)访问。

class A():
    def __init__(self):
        self.x = 'hello'

print A.x -> AttributeError
print A().x -> 'hello'

在第二个例子中,有一个静态变量。由于类A的名称,您可以访问此变量

class A():
  x = 'hello'

print A.x -> 'hello'
print A().x -> 'hello'

实际上,可以有一个静态变量和一个同名的实例变量:

class A():
    x = 'hello'
    def __init__(self):
        self.x = 'world'

print A.x -> hello
print A().x -> world

静态值在所有实例之间共享

class A():
    x = 'hello'

    @staticmethod
    def talk():
        print A.x

a = A()
print a.talk() -> hello

A.x = 'world'
print a.talk() -> world

你在这里有一篇好文章: http://linuxwell.com/2011/07/21/static-variables-and-methods-in-python/

相关问题 更多 >