繁体   English   中英

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

[英]In python, how to overload return/get based on return type?

在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 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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM