我想像这样定义一个函数:
def x(a, b):
#do stuff
但是让它可以这样调用:
num1=1
num2=2
num1.x(num2)
有办法做到这一点吗?
最佳答案
不,你想要的只能通过Python中的方法来实现。它不像 C++,您可以在类之外定义“非成员”方法(我不确定这是否是这些方法的名称,但我希望您知道我的意思)。
此外,Python 整数(还有 float 、字符串等)不支持新的属性/方法,因此实现这一点的唯一方法是实际子类化该类或创建一个新类:
class MyClass(object): # a custom class
def __init__(self, val):
self.val = val
def x(self, other):
return self.__class__(self.val + other.val)
def __repr__(self):
return '{self.__class__.__name__}({self.val})'.format(self=self)
>>> n1 = MyClass(1)
>>> n2 = MyClass(2)
>>> n1.x(n2)
MyClass(3)
关于python - 如何定义一个函数以便可以在对象上调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46080387/