difference between variables inside and outside of __init__()

前端 未结 10 771
醉酒成梦
醉酒成梦 2020-11-22 17:08

Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = \"Bob\"
    def my_fu         


        
10条回答
  •  耶瑟儿~
    2020-11-22 17:44

    This is very easy to understand if you track class and instance dictionaries.

    class C:
       one = 42
       def __init__(self,val):
            self.two=val
    ci=C(50)
    print(ci.__dict__)
    print(C.__dict__)
    

    The result will be like this:

    {'two': 50}
    {'__module__': '__main__', 'one': 42, '__init__': , '__dict__': , '__weakref__': , '__doc__': None}
    

    Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

    This is all you should know about that specific variables.

提交回复
热议问题