Attributes initialization/declaration in Python class: where to place them?

前端 未结 2 526
孤街浪徒
孤街浪徒 2020-12-05 01:57

I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function?

i.e.<

2条回答
  •  春和景丽
    2020-12-05 02:25

    If you want the attribute to be shared by all instances of the class, use a class attribute:

    class A(object):
        foo = None
    

    This causes ('foo',None) to be a (key,value) pair in A.__dict__.

    If you want the attribute to be customizable on a per-instance basis, use an instance attribute:

    class A(object):
       def __init__(self):
           self.foo = None
    

    This causes ('foo',None) to be a (key,value) pair in a.__dict__ where a=A() is an instance of A.

提交回复
热议问题