Usefulness of def __init__(self)?

后端 未结 3 433
夕颜
夕颜 2021-02-02 06:51

I am fairly new to python, and noticed these posts: Python __init__ and self what do they do? and Python Classes without using def __init__(self)

After playing around w

3条回答
  •  深忆病人
    2021-02-02 07:41

    Yeah, check this out:

    class A(object):
        def __init__(self):
            self.lst = []
    
    class B(object):
        lst = []
    

    and now try:

    >>> x = B()
    >>> y = B()
    >>> x.lst.append(1)
    >>> y.lst.append(2)
    >>> x.lst
    [1, 2]
    >>> x.lst is y.lst
    True
    

    and this:

    >>> x = A()
    >>> y = A()
    >>> x.lst.append(1)
    >>> y.lst.append(2)
    >>> x.lst
    [1]
    >>> x.lst is y.lst
    False
    

    Does this mean that x in class B is established before instantiation?

    Yes, it's a class attribute (it is shared between instances). While in class A it's an instance attribute. It just happens that strings are immutable, thus there is no real difference in your scenario (except that class B uses less memory, because it defines only one string for all instances). But there is a huge one in my example.

提交回复
热议问题