Call a method as property or function?

一个人想着一个人 提交于 2021-01-28 09:56:04

问题


Is it possible to have a method and call it as either function or property?

def Foo:
  def bar(self,x=1,y=2):
    return x+y

foo=Foo()
foo.bar #should return 3
foo.bar(4,5) #should return 9

It seems to be impossible, because:

  • foo.bar will call __getattribute__; if it's a descriptior, __get__ will be called from within __getattribute__, meaning that bar() is evaluated before it's even returned to the caller
  • if an attribute is a function, it only returns a function and then () is applied to that function
  • because of that, it's impossible to detect in __getattribute__ if caller is calling a property or function
  • hence, dual behaviour is not possible

What I hopped to implement is something like (pseudocode):

def __getattribute__():
   if len(args)>1: return function
   else: return property

But because args are not passed to __getattribute__ or __get__, I don't know where and how to switch between property and function.


回答1:


Just use:

foo.bar() # 3
foo.bar(4, 5) # 9

If you do insist, here is a very ugly, unusable solution, that wil actually return 3 and 9. Works on python 3.6. Don't use it:

class CallableInt(int):
    """But, why????"""
    def __call__(self, x, y):
        return x + y


class Foo:
    @property
    def bar(self):
        return CallableInt(3)


foo = Foo()
print(foo.bar)
print(foo.bar(4, 5))


来源:https://stackoverflow.com/questions/42899319/call-a-method-as-property-or-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!