全局类成员仅在python中实例化一次

时间:2017-12-20 10:58:04

标签: python python-3.x

以下代码,

class A:
  pass

class B:
  member = A()

  def hello(self):
    print(repr( type(self).member ))

b1 = B()
b2 = B()

b1.hello()
b2.hello()

给出以下输出:

<__main__.A object at 0x0000025193C03DA0>
<__main__.A object at 0x0000025193C03DA0>

似乎python只实例化A一次,并将其值用于B的所有实例。为什么会发生这种情况,是否有办法为B的所有实例实例化不同的全局成员?

0 个答案:

没有答案