是否可以重载类型方法的return?
Is it possible to overload the return of the type method?
给定以下示例:
class Container:
def __init__(self, var):
self.var = var
class Test:
def __init__(self):
self.var = Container("123")
是否可以重载 type()
方法,例如 type(Test().var)
会产生 string
而不是 Container
?
编辑:我正在使用容器 class 来限制 Test.var.
想法是Test是一个class,包含很多变量,有些有相似的名字。 Container class 用于确保使用正确的类型( __eq__(), __str__(), __add__(), ... 被重载以便使容器 class 尽可能谨慎)以便尽快诊断问题(代码将由 python 中具有广泛专业知识的人使用)
另一个解决方案是使用 @property
但由于有很多变量,代码最终会比其他方式大得多并且维护起来也不那么简单(有将近一百个classes 将必须实施属性 )
我想重载 type(Test().var)
以便 return type(Test().var.var)
尽可能易于使用
简短的回答是"no."
来自 this official Python doc,它指出:
Every object has an identity, a type and a value... The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.
给定以下示例:
class Container:
def __init__(self, var):
self.var = var
class Test:
def __init__(self):
self.var = Container("123")
是否可以重载 type()
方法,例如 type(Test().var)
会产生 string
而不是 Container
?
编辑:我正在使用容器 class 来限制 Test.var.
想法是Test是一个class,包含很多变量,有些有相似的名字。 Container class 用于确保使用正确的类型( __eq__(), __str__(), __add__(), ... 被重载以便使容器 class 尽可能谨慎)以便尽快诊断问题(代码将由 python 中具有广泛专业知识的人使用)
另一个解决方案是使用 @property
但由于有很多变量,代码最终会比其他方式大得多并且维护起来也不那么简单(有将近一百个classes 将必须实施属性 )
我想重载 type(Test().var)
以便 return type(Test().var.var)
尽可能易于使用
简短的回答是"no."
来自 this official Python doc,它指出:
Every object has an identity, a type and a value... The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.