还有其他方法可以创建“参数化”类吗?

时间:2019-07-12 07:11:05

标签: python class inheritance

假设我有这样的课程:

class A(object):
    PREFIX = "1"
    text = "%s) some text" % PREFIX

现在我想创建一个具有更改的PREFIX的祖先

class B(A):
    PREFIX = "2"
    other_field = "other text"

但这不能正常工作

a = A()
b = B()
print(a.text)  # 1) some text
print(b.text)  # 1) some text

我知道为什么。好吧,我想出了如何做事...

# And now for something (not really) completely different...

def factory(prefix):
    class Meta(object):
        text = "%s) some text" % prefix
    return Meta

A = factory(prefix="1")

class B(factory(prefix="2")):
    other_field = "other text"

a = A()
b = B()

print(a.text)  #1) some text
print(b.text)  #2) some text

...但是在我看来,这有点丑陋。 有没有更好的方法来做这种事情?还是我对丑陋只是错了?

我尝试过混音,但是没有运气。

注意:由于某种原因,我无法在构造函数中初始化PREFIX,我只需要在类定义中对属性初始化进行参数化

2 个答案:

答案 0 :(得分:1)

您可以使用描述符(__get__方法-doc)实现类似的目的:

class prefixed_text:
    def __init__(self, s):
        self.s = s

    def __get__(self, obj, _type=None):
        return self.s.format(_type.PREFIX)

class A:
    PREFIX = "1"
    text = prefixed_text("{}) some text")

class B(A):
    PREFIX = "2"

#classes:
print(A.text)
print(B.text)

#instances:
print(A().text)
print(B().text)

打印:

1) some text
2) some text
1) some text
2) some text

答案 1 :(得分:0)

您可以将属性text设置为属性(这是创建描述符的一种简便方法):

class A(object):
    PREFIX = "1"
    @property
    def text(self):
        return "%s) some text" % self.PREFIX


class B(A):
    PREFIX = "2"
    other_field = "other text"


a = A()
b = B()
print(a.text)  # -> 1) some text
print(b.text)  # -> 2) some text