简体   繁体   中英

Are class fields inherited in 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

//Update:

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

How to explain the result.

Seems like C and A has a different copy of a. In C++ a static member is expected to be shared with its derived class.

Martin Konecny's answer is mostly correct. There are class-level attributes (which are like static members) and instance-level attributes. All instances share their class attributes (but not their instance attributes), and they can be changed dynamically. Somewhat confusingly, you can get class attributes from an instance with the dot-notation, unless an instance attribute is defined with the same name. Perhaps these examples are illustrative:

 >>> 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

In python there is a class attribute and an instance attribute

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

Seems like C and A has a different copy of a.

Correct. If you're coming from Java, it's helpful to think of class A as a "static" field, and class C as an "instance" field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM