我有一门课是这样的:
Class PropertyExpr:
def __init__(self, value, expr):
self.value = value
self.expr = expr
假设我像这样初始化类:
prop1 = PropertyExpr(5, "test")
我知道如果我想访问value
或expr
,我会调用prop1.value
或prop1.expr
但是,我希望这样,无论何时调用prop1
,它都会自动返回prop1.value
prop1.expr
仍然可以访问expr
变量
由于value
可以是任何数据类型,我认为使用__str__
是行不通的
谢谢你的帮助
编辑:这是我当前的方法,但它只适用于int,我需要扩展它,以便它也适用于其他数据类型,例如list:
class PropertyExpr(int):
def __new__(self, value: int, expr: Optional[str]=None, *args, **kwargs):
return int.__new__(self, value, *args, **kwargs)
def __init__(self, value: int, expr: Optional[str]=None, *args, **kwargs):
int.__init__(value, *args, **kwargs)
if expr is None:
self.expr = str(value)
else:
self.expr = expr
因此,当我创建实例时:
prop1 = PropertyExpr(5, "test")
因此,当我使用prop1
时,它将返回5和prop1.expr = "test"
您可以这样做:
输出:
如果“call”实际上指的是call而不仅仅是“access”,那么您可以简单地实现一个
__call__
方法:输出:
在这种情况下,调用
prop1()
的结果实际上可以是任何东西除此之外,你想要的是不可能的。您可以重写
__new__
方法,但这也会更改所创建内容的类型。因此,如果您返回5
,您的对象将是5
,但它也将是int
,不再是PropertyExpr
的实例,并且所有附加属性都将丢失:输出:
经过一些尝试,我找到了一种动态更改构造函数类型的方法,但是我建议不要实际使用:
输出:
您可以将希望子类的类型作为第一个参数传递,第二个参数应该是该类型的构造函数接受的值,然后您可以传递任意KWARG,这些KWARG将作为属性添加到创建的对象中
我不能让它工作(这并不意味着其他人不能),但我设法使它与多重继承一起工作,因此您可以使用
isinstance(prop1, PropertyExprMixin)
:输出:
相关问题 更多 >
编程相关推荐