设置类变量类实例

问题描述 投票:0回答:1

在A类中,我希望一些“特殊”值存储为类变量。出于无法理解的原因,以下内容无效:

class A:

   def __init__(self, msg):
        self.s = msg

   X = A("special message")

我可以使用:

class A:

   def __init__(self, msg):
        self.s = msg

A.X = A("special message")  # outside of the class

但是它看起来很不整洁,很容易被遗忘(假设A类很长)。有没有一种巧妙的方法可以在类本身内部使用A的实例来初始化A的类变量?

python class-variables
1个回答
0
投票

是否有一种巧妙的方法可以在类本身内部使用A的实例来初始化A的类变量?

不,您不能使用相同类的实例在类内部]初始化类属性,因为在执行类的主体时未定义您的类。但是也许您可以使用装饰器。我不确定是否比A.X = A("special message")更喜欢它,但是在这里您可以:

def add_class_property(arg):
    class ClassWrapper:
        def __init__(self, cls):
            self.other_class = cls
            self.X_ = cls(arg)

        @property
        def X(self):
            return self.X_

        def __call__(self, *cls_ars):
            return self.other_class(*cls_ars)

    return ClassWrapper


@add_class_property("special message")
class A:
    def __init__(self, msg):
        self.s = msg

    def __str__(self):
        return self.s


print(A.X) 
# special message
© www.soinside.com 2019 - 2024. All rights reserved.