1
class C2:
  x = 2
  z = 2

class C3:
  w = 3
  z = 3

  def __init__(self):
    self.w += 1

class C1(C2, C3):
  x = 1
  y = 1

I1 = C1()
I1.name = 'I1'

I2 = C1()
I2.name = 'I2'

print I1.w  # 4
print I2.w  # 4
print C3.w  # 3

你能解释一下最近 3 次打印的结果吗?我找不到这个逻辑:)

4

2 回答 2

2

I'm not sure how self.w += 1 will create an instance variables instead of just increment class variable or raise an exception for missing instance variable?

这可能有助于您理解它:

>>> class Foo:
...  x = 1
...  def __init__(self):
...   print 'self =', self
...   print 'self x =', self.x
...   print 'foo x =', Foo.x
...   print self.x is Foo.x
...   Foo.x = 2
...   self.x = 3
...   print 'self x =', self.x
...   print 'foo x =', Foo.x
... 
>>> a = Foo()
self = <__main__.Foo instance at 0x1957c68>
self x = 1
foo x = 1
True
self x = 2
foo x = 3
>>> print a
<__main__.Foo instance at 0x1957c68>
于 2013-08-14T13:56:26.313 回答
0

我不确定你对什么感到困惑。C3定义了 __init__增加 的值的方法self.w。因此,两个实例都将获得值为 的实例变量4,而类对象本身有一个值为 的类变量3

于 2013-08-14T13:51:22.967 回答