python: class attributes and instance attributes

后端 未结 6 985
滥情空心
滥情空心 2020-12-01 19:54

I\'m new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code:

>>&g         


        
6条回答
  •  天命终不由人
    2020-12-01 20:08

    >>> class Foo:
    ...     a=1
    ... 
    >>> f1=Foo()
    >>> f2=Foo()
    >>> f1.a    # no instance attribute here in f1, so look up class attribute in Foo
    1
    >>> f1.a=5  # create new instance attribute in f1
    >>> f1.a    # instance attribute here. Great, let's use this.
    5
    >>> f2.a    # no instance attribute in f2, look up class attribute in Foo
    1
    >>>
    >>> class Foo:
    ...     a=[]
    ... 
    >>> f1=Foo()
    >>> f2=Foo()
    >>> f1.a            # no instance attribute - look up class attribute in Foo
    []
    >>> f1.a.append(5)  # no instance attribute, modify class attribute in-place
    >>> f1.a            # no instance attribute - look up class attribute in Foo
    [5]
    >>> f2.a            # same here
    [5]
    

提交回复
热议问题