Difference between defining a member in __init__ to defining it in the class body in python?

后端 未结 3 532
广开言路
广开言路 2021-01-12 11:37

What is the difference between doing

class a:
   def __init__(self):
       self.val=1

to doing

class a:
   val=1
   def __         


        
3条回答
  •  清歌不尽
    2021-01-12 12:32

    As mentioned by others, in one case it's an attribute on the class on the other an attribute on the instance. Does this matter? Yes, in one case it does. As Alex said, if the value is mutable. The best explanation is code, so I'll add some code to show it (that's all this answer does, really):

    First a class defining two instance attributes.

    >>> class A(object):
    ...     def __init__(self):
    ...         self.number = 45
    ...         self.letters = ['a', 'b', 'c']
    ... 
    

    And then a class defining two class attributes.

    >>> class B(object):
    ...     number = 45
    ...     letters = ['a', 'b', 'c']
    ... 
    

    Now we use them:

    >>> a1 = A()
    >>> a2 = A()
    >>> a2.number = 15
    >>> a2.letters.append('z')
    

    And all is well:

    >>> a1.number
    45
    >>> a1.letters
    ['a', 'b', 'c']
    

    Now use the class attribute variation:

    >>> b1 = B()
    >>> b2 = B()
    >>> b2.number = 15
    >>> b2.letters.append('z')
    

    And all is...well...

    >>> b1.number
    45
    >>> b1.letters
    ['a', 'b', 'c', 'z']
    

    Yeah, notice that when you changed, the mutable class attribute it changed for all classes. That's usually not what you want.

    If you are using the ZODB, you use a lot of class attributes because it's a handy way of upgrading existing objects with new attributes, or adding information on a class level that doesn't get persisted. Otherwise you can pretty much ignore them.

提交回复
热议问题