简体   繁体   English

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

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

PyGithub does not appear to support the GitHub API call to acquire the latest release . PyGithub似乎不支持GitHub API调用来获取最新版本 I'm wondering if I can add a method to PyGithub at run time that would do this for me. 我想知道是否可以在运行时为PyGithub添加一个方法来为我做这件事。

For example, the existing code has the following method: 例如,现有代码具有以下方法:

# 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
    )

I'd like to add this one to the Repository.py class: 我想将此添加到Repository.py类:

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

I tried this but I received an error: 我尝试了这个,但是收到一个错误:

# 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'

Is it possible to add this method at runtime? 是否可以在运行时添加此方法?

Assigning directly to Repository.get_latest_release should be sufficients, eg: 直接分配给Repository.get_latest_release应该足够,例如:

Repository.get_latest_release = get_latest_release

You would only need MethodType if you were trying to assign to an instance, eg 如果您尝试分配给实例,则只需要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)

Where class assignment is available to all instances of that class, instance assignment is not: 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