带有inheritan的Python类属性

2024-04-25 06:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这里的情况有点怪。有没有可能在python中设置一个带有继承的“classproperty”?你知道吗

我有以下情况。我有一个具有很多功能的基类。我已经用classmethod“instantiate\u from \u somewhere \u”覆盖了构造函数。现在这个构造函数必须使用一个值,这个值是在类上设置的。我目前正在通过另一个classmethod实现这一点。 但是,我觉得这很难看,我更希望能够访问myu prop而不必调用方法(即use)cls.my\u道具或者自我。我的道具而不是cls.my\u道具()和自我。我的道具())

class base(object):
    def __init__(self,**kwargs):
        ... do things

    @classmethod
    def my_prop(cls):
        return 'base'

    def func_to_use_property(self):
        print(self.my_prop())

    @classmethod
    def instantiate_from_somewhere_else(cls,**kwargs):
        res = call_external(cls.my_prop(),**kwargs)
        return cls(res)


class sub(base):
    @classmethod
    def my_prop(cls)
        return 'child'

好像我脑子有点迟钝。这似乎起到了作用:

class Base(object):
    my_prop = 'base'

    def instantiate_from_somewhere_else(self):
        return self.__class__.my_prop

class Derived(Base):
    my_prop = 'derived'

Tags: fromselfbasereturnmydef情况kwargs