python - 如何定义一个函数以便可以在对象上调用它?

标签 python python-3.x list function methods

我想像这样定义一个函数:

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/

相关文章:

python - 当 PyQt5 应用程序退出时,我得到 "Release of profile requested but WebEnginePage still not deleted. Expect troubles !"

python - 属性错误 : 'TextTestResult' object has no attribute 'assertIn'

java - 如何将BST的所有数据存储到一个数组列表中?

android - Google Glass 上的 ListView

Python - 如何按照指定的属性顺序对对象数组进行双重排序?

python - 是否可以将 Python 模块(.py 文件)导入字典?

python - Django 通过列表中的值从数据库中查找项目?

python-3.x - 如何在列表的解析参数中解析列表(字符串)而不是列表(字符)?

python - 在 Python 和 Oracle 11g 中通过 cur.fetchall() 下载数组

python - 在数据框中的列中的特定位置添加字符串