在Python中重载子类化int的返回值

时间:2018-04-06 09:54:26

标签: python subclassing

我想在请求子类化int的值时调用函数。据我所知,通过__getattribute__间接请求类的任何属性,但似乎内置类的不可变值通过其他方式访问,因为重载它不会影响返回行为。解释为什么会这样,以及返回值如何与其他类属性(以及对文档的引用)不同,将非常感激。

作为一个例子,我在int的子类中放置什么来让交互式解释器返回以下内容?:

>>> class IntSub(int):
...   def before(self):
...     print "value requested"
...   def after(self):
...     print "value returned"
... 
>>> intsub1 = IntSub(42)
>>> intsub2 = intsub1
value requested
value returned
>>> 

修改

我找到了几种方法来获得我寻求的解决方案的一半,尽管不是没有调用返回对象的方法。

1:将get()添加到IntSub并在进行分配时调用它,我的第一个解决条件就满足了:

...   def get(self):
...     self.before()
...     print "returning value"
...     return self
...
>>> subint1 = SubInt(42)
>>> subint2 = subint1.get()
value requested
returning value
>>>

2:在get()上使用函数装饰器,通过跳过几个环节也可以满足我的第二个条件:

...   def decorate(decorating):
...     def decorated(self):
...       self.before()
...       result = decorating(self)
...       self.after()
...       return result
...     return decorated
...   @decorate
...   def get(self):
...     print "returning value"
...     return self
...     
>>> intsub1 = IntSub(42)
>>> intsub2 = intsub1.get()
value requested
returning value
value obtained
>>> 

尽管如此,问题仍然是这些方法需要添加get(),这并不令人满意。我想知道我想要的解决方案是否可以使用类装饰器或不同的元类来实现。建议和建议非常受欢迎。

0 个答案:

没有答案