Python 如何向类中的方法添加方法?
假设我有以下课程:Python 如何向类中的方法添加方法?,python,python-3.x,Python,Python 3.x,假设我有以下课程: import webbrowser class Management(object): def add_accounts(self, data): operations = [] for account_name in data: operations.append( {'operator': 'ADD', 'operand': {'name': account_name} })
import webbrowser
class Management(object):
def add_accounts(self, data):
operations = []
for account_name in data:
operations.append(
{'operator': 'ADD',
'operand': {'name': account_name}
})
self.added = operations
manager = Management()
manager.add_accounts(['name 1', 'name 2'])
我要做的是添加此函数:
def source():
url = r'http://www.stackoverflow.com/some-help-doc'
webbrowser.open(url, new=1)
添加到add_accounts
方法,以便我可以键入以下内容:
manager.add_accounts.source()
并使其打开联机帮助文章的默认浏览器:
我一直在寻找如何向类中已经存在的方法添加方法。我要做的事情有没有名字?正如@BrenBam在评论中指出的那样,方法确实有属性,这些属性可以是任何东西,包括函数。然而,这会产生一些奇怪的非Python代码。如果您希望此方法显示某种文档(如示例所示),最好只将信息复制粘贴到docstring。Docstring是每个人都希望信息出现的地方。这似乎是目前最好的选择:
import webbrowser
class Management(object):
def __init__(self):
Management.add_accounts.source = lambda url='https://github.com/': webbrowser.open(url, new=1)
def add_accounts(self, data):
operations = []
for account_name in data:
operations.append(
{'operator': 'ADD',
'operand': {'name': account_name}
})
self.added = operations
manager = Management()
在Python3中,您可以执行
Management.add\u accounts.source=source
。它不是一种添加账户的方法,它只是一个存储在属性添加账户
中的函数。但你为什么要这么做?通过这种特殊的方式访问它,您会得到什么?请记住,Python可以完成很多事情,我想这样做是因为我使用的是API,类中的每个方法都需要非常具体的操作构造dict
。我在这个类中有很多方法,所以能够快速获取在线文档对我很有帮助。我希望能够在类内而不是类外添加source
。添加此函数的全部目的是为了不必复制/粘贴文档。我理解。但是当有人使用你的代码时,他们会做什么来获取信息呢?他们将键入打印(管理.添加帐户.\uuu文档)
。只要将Github上的内容复制粘贴到docstring中,就可以了。