在python中,如何根据返回类型重载返回/获取?



在python中,是否可以重载返回类型?基本上,我正在尝试看看我是否可以做这样的事情:

class Node(object):
def __init__(self):
self.value = 5
def hello(self):
print('hello')
class Container(object):
def __init__(self):
self.node = Node()
def __setattr__(self, name, value):
if self.__dict__.get(name, False) and name == 'node':
obj = getattr(self, name)
obj.value = value
else:
self.__dict__[name] = value
# some method overloading... to return base on type
container = Container()
container.node = 3
print (container.node.value) # outputs 3
int_val = 0
int_val = container.node  # assign int_val to 3
container.node.hello() # prints out 'hello'

这是不可能的。 您可以定义一个__int__方法来指定在类的实例上调用int时应发生的情况,以便int(container.node)为 3。 但是你不能让container.node实际上是3,而container.node.hello()container.node部分是另一回事。container.node.hello()中属性引用的计算从左到右进行,因此container.node计算时不会"知道"您稍后将尝试对其调用方法。

正如帕特里克·霍(Patrick Haugh(在他的回答中所建议的那样,你可以对int进行子类化,这样container.node的行为就像数字3一样,但也有一个.hello()的方法。 但是,您仍然不会导致container.node在不同的上下文中具有不同的值;您使它具有一个值,该值在两个上下文中组合了所需的功能。 该值实际上不是3而是 Node 实例,这在某些情况下可能很重要。 尽管如此,这通常是一种合法的方式,可以实现与您似乎想要的效果类似的效果。

也可以使用__setattr__,以便container.node = 3将值设置为 3 以外的值(例如,某个包装器对象(,但这不会更改上述内容。 当您计算container.node时,它在所有上下文中只能有一个值。

下面,我做了一个Node类,它是int的子类,基本上只是添加一个hello方法。Container使用propertyint价值观转化为幕后Node

class Node(int):
def __new__(cls, value, *args, **kwargs):
return super(Node, cls).__new__(cls, value, *args, **kwargs)
def hello(self):
print("Hello!")
class Container(object):
def __init__(self):
self.node = 5
@property
def node(self):
return self._node
@node.setter
def node(self, value):
self._node = Node(value)
container = Container()
container.node = 3
print(container.node)  # 3
container.node.hello()  # Hello!

最新更新