【问题标题】:Create static attribute of class (attribute is instance of that same class)创建类的静态属性(属性是同一类的实例)
【发布时间】:2018-11-27 11:40:38
【问题描述】:

假设我有一个定义如下的类:

class Foo():
   baz = None
   def __init__(self, bar):
       self.bar = bar

现在,在该示例中,Foo.bazNone。现在假设这个类属性需要是Foo 的一个实例,如下所示:

class Foo():
    baz = Foo("baz")
    def __init__(self, bar):
        self.bar = bar

我将如何进行?

同样,有没有办法创建“类属性”。我知道我可以将返回类的新实例的 lambda 函数分配给类属性,但我宁愿不必写括号。

【问题讨论】:

    标签: python oop static


    【解决方案1】:

    如果你想在一个类中使用baz = Foo("baz")这一行,甚至在之前定义Foo之前;这是不可能的,即 Python 会向你抛出 NameError: name 'Foo' is not defined,但这里有一个解决方法来实现你想要的:

    class Foo:
       def __init__(self, bar):
           self.bar = bar
    Foo.baz=Foo('foo')
    

    现在Foo.bazFoo 类的一个实例,baz 也是Foo 类的一个类属性,因此也将被该类的所有实例继承:

    myFoo = Foo('myFoo')
    

    您可以验证 myFoo.baz.bar 实际上是 'foo' 而不是 'myFoo'

    print(myFoo.bar) 
    # myFoo
    print(myFoo.baz.bar)
    # foo
    

    还请注意,这将导致Foo.bazFoo.baz.bazFoo.baz.baz.baz 等都成为Foo 对象,因为Foo.baz 具有值Foo('foo'),即Foo 类和@987654341 的对象@也是Foo的类属性。

    【讨论】:

      猜你喜欢
      • 2011-06-11
      • 2019-06-28
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2020-09-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多