类字段是否在python中继承?

时间:2014-06-05 02:07:11

标签: python

class A:
    a = 3
    def f(self):
        print self.a

class C(A):
    def __init__(self):
        self.a = 4

>>> a=A()
>>> a.f()
3
>>> c = C()
>>> a.f()
3
>>> c.f()
4

//更新:

>>> C.a = 5
>>> A.a
3
>>> c.a
4

如何解释结果。

似乎C和A有一个不同的副本。在C ++中,期望静态成员与其派生类共享。

2 个答案:

答案 0 :(得分:2)

Martin Konecny的answer大多是正确的。有类级属性(类似于静态成员)和实例级属性。所有实例共享其类属性(但不是它们的实例属性),并且可以动态更改它们。有点令人困惑的是,除非使用相同的名称定义实例属性,否则可以使用点符号从实例获取类属性。也许这些例子是说明性的:

 >>> class A:
 ...     a = 3
 ...     def f(self):
 ...         print self.a
 ...
 >>> class C(A):
 ...     def __init__(self):
 ...         self.a = 4
 ...
 >>> a = A()
 >>>
 >>> A.a  # class-level attribute
 3
 >>> a.a  # not redefined, still class-level attribute
 3
 >>> A.a = 5  # redefine the class-level attr
 >>> A.a  # verify value is changed
 5
 >>> a.a  # verify instance reflects change
 5
 >>> a.a = 6  # create instance-level attr
 >>> A.a  # verify class-level attr is unchanged
 5
 >>> a.a  # verify instance-level attr is as defined
 6
 >>> a.__class__.a  # you can still get the class-level attr
 5
 >>>
 >>> c1 = C()
 >>> c2 = C()
 >>> C.a  # this changed when we did A.a = 5, since it's inherited
 5
 >>> c1.a  # but the instance-level attr is still there
 4
 >>> c2.a  # for both instances
 4
 >>> c1.a = 7  # but if we change one instance
 >>> c1.a  # (verify it is set)
 7
 >>> c2.a  # the other instance is not changed
 4

答案 1 :(得分:1)

在python中有一个class属性和一个实例属性

class A:
    a = 3 # here you are creating a class attribute
    def f(self):
        print self.a

class C(A):
    def __init__(self):
        self.a = 4 #here you are creating an instance attribute
  

似乎C和A有不同的副本。

正确。如果您来自Java,将A类视为“静态”字段,将C类视为“实例”字段会很有帮助。