Python - 在对象实例化期间设置类属性(构造)

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

我有一个属性必须只设置一次的类(让我们通过命令行参数说)。从那以后它是不可改变的。

class Example(object):
    _classattribute = None

我这样做是通过读取命令行参数,并在对象构造期间将它们作为参数传递。根据classatribute,我返回一个不同的对象Type。

class Example(object):
    _classattribute = None
    _instance = None

    def __new__(cls, attribute=None):
        if not cls._clsattribute:
             if not attribute:
                raise ValueError('class attribute not set')
            cls._clsattribute = attribute
        if cls._classatribute == condition1:
            cls._instance = Type1(cls._classattribute)
        if cls._classatribute == condition2:
            cls._instance = Type2(cls._classattribute)
        return cls._instance


class Type1:
    def __init__(self, property):
        self.property = property

class Type2:
    def __init__(self, property):
        self.property = property

在对象构建期间,这是第一次:

eg1 = Example("This is type1 attribute")

随后构建对象:

eg2 = Example()

这是一个我不能说的好方法。这对我来说太明确了。除了类属性_claassattribute的一次设置之外,它类似于Borg,共享状态模式。

任何形式的批评/反馈/思想/建议都是受欢迎的。

python-3.x oop
1个回答
0
投票

这是个人设计选择,但我对此的看法是,__new__应该总是返回班级或None的对象。在您的代码中,如果它永远不会返回自己的实例,则没有理由使用class。你可能想要的东西包括一个返回Type1Type2对象的工厂。

def get_type_factory(attribute):

    if attribution == condition1:
        return lambda: Type1(attribute)
    elif attribute == condition2:
        return lambda: Type2(attribute)
    else:
        raise ValueError

# Can be used like so
factory = get_type_factory('foo')

type_object1 = factory()
type_object2 = factory()
© www.soinside.com 2019 - 2024. All rights reserved.