属性在Python类初始化/声明:在什么地方呢? [英] Attributes initialization/declaration in Python class: where to place them?
问题描述
我想知道什么是初始化对象在Python属性的最佳实践,在类的主体或 __里面的init __
功能?
即
A类(对象):
富=无
VS
A类(对象):
高清__init __(个体经营):
self.foo =无
如果您希望属性由该类的所有实例共享,使用一个类属性:
A类(对象):
富=无
这使得('富',无)
是一个(键,值)
一对 A .__字典__
。
如果你想要的属性可定制的每个实例的基础上,使用实例属性:
A类(对象):
高清__init __(个体经营):
self.foo =无
这使得('富',无)
是一个(键,值)
一对 A .__字典__
,其中 A = A()
是一个实例 A
。
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.
class A(object):
foo = None
vs
class A(object):
def __init__(self):
self.foo = None
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
.
这篇关于属性在Python类初始化/声明:在什么地方呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!