繁体   English   中英

如何在运行时使用Python将方法添加到外部类?

[英]How to add a method to an external class at runtime in Python?

PyGithub似乎不支持GitHub API调用来获取最新版本 我想知道是否可以在运行时为PyGithub添加一个方法来为我做这件事。

例如,现有代码具有以下方法:

# Repository.py
def get_releases(self):
    """
    :calls: `GET /repos/:owner/:repo/releases <http://developer.github.com/v3/repos>`_
    :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Tag.Tag`
    """
    return github.PaginatedList.PaginatedList(
        github.GitRelease.GitRelease,
        self._requester,
        self.url + "/releases",
        None
    )

我想将此添加到Repository.py类:

def get_latest_release(self):
    return github.PaginatedList.PaginatedList(
        github.GitRelease.GitRelease,
        self._requester,
        self.url + "/releases/latest",
        None
    )

我尝试了这个,但是收到一个错误:

# main.py

from types import MethodType
from github import Github
from github.Repository import Repository, github

def get_latest_release(self): ...

def main():
    Repository.method = MethodType(get_latest_release, None, Repository)
    g = Github(<my name>, <my password>)
    org = g.get_organization(<name of org>)
    repo = org.get_repo(<name of repository>)
    release = repo.get_latest_release()

    # AttributeError: 'Repository' object has no attribute 'get_latest_release'

是否可以在运行时添加此方法?

直接分配给Repository.get_latest_release应该足够,例如:

Repository.get_latest_release = get_latest_release

如果您尝试分配给实例,则只需要MethodType

>>> import types
>>> class A(object):
...     pass
>>> a = A()
>>> A.one = lambda self: 1
>>> a.two = types.MethodType(lambda self: 2, a)
>>> a.one(), a.two()
(1, 2)

class分配可用于class所有实例的情况下, instance分配不是:

>>> b = A()
>>> b.one()
1
>>> b.two()
AttributeError: 'A' object has no attribute 'two'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM