[英]Create static attribute of class (attribute is instance of that same class)
Let's say I have a class defined as follow : 假设我有一个定义如下的类:
class Foo():
baz = None
def __init__(self, bar):
self.bar = bar
Now, in that example Foo.baz
is None
. 现在,在该示例中, Foo.baz
为None
。 Now let's say that this class attribute needs to be an instance of Foo
like below: 现在让我们说这个类属性必须是Foo
一个实例,如下所示:
class Foo():
baz = Foo("baz")
def __init__(self, bar):
self.bar = bar
How would I proceed? 我将如何进行?
Similarly, is there any way to create a "class property". 同样,有什么方法可以创建“类属性”。 I know I can assign a lambda function returning a new instance of the class to a class attribute, but I'd rather not have to write the parenthesis. 我知道我可以分配一个lambda函数,将类的新实例返回给class属性,但是我宁愿不必编写括号。
If you want to use the line baz = Foo("baz")
inside a class even before defining Foo
earlier; 如果要在类中甚至早于定义Foo
之前使用行baz = Foo("baz")
。 it's not possible ie Python will throw a NameError: name 'Foo' is not defined
at you, but here's a workaround to achieve what you intend: 这是不可能的,即Python会抛出NameError: name 'Foo' is not defined
,但这是一种实现您想要的解决方法:
class Foo:
def __init__(self, bar):
self.bar = bar
Foo.baz=Foo('foo')
Now Foo.baz
is an instance of the Foo
class and also baz
is a class attribute of the Foo
class and hence will be inherited by all instances of the class as well: 现在Foo.baz
是实例Foo
阶级,也baz
是一个类属性Foo
类,因此将通过为好类的所有实例继承:
myFoo = Foo('myFoo')
You can verify that myFoo.baz.bar
is infact 'foo'
and not 'myFoo'
您可以验证myFoo.baz.bar
是'foo'
而不是'myFoo'
print(myFoo.bar)
# myFoo
print(myFoo.baz.bar)
# foo
Also note that this will cause Foo.baz
, Foo.baz.baz
, Foo.baz.baz.baz
etc. all to be a Foo
object because Foo.baz
has value Foo('foo')
ie an object of Foo
class and baz
is also a class attribute of Foo
. 还要注意,这将导致Foo.baz
, Foo.baz.baz
, Foo.baz.baz.baz
等全部成为Foo
对象,因为Foo.baz
具有值Foo('foo')
即Foo
类的对象和baz
也是Foo
的类属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.