python类的动态方法是什么_如何在python中为类动态创建类方法
如果我將一個(gè)小python程序定義為class a():
def _func(self):
return "asdf"
# Not sure what to resplace __init__ with so that a.func will return asdf
def __init__(self, *args, **kwargs):
setattr(self, 'func', classmethod(self._func))
if __name__ == "__main__":
a.func
我收到回溯錯(cuò)誤Traceback (most recent call last):
File "setattr_static.py", line 9, in
a.func
AttributeError: class a has no attribute 'func'
我想知道的是,如何在不實(shí)例化對(duì)象的情況下動(dòng)態(tài)地將類方法設(shè)置為類?
編輯:
這個(gè)問(wèn)題的答案是class a():
pass
def func(cls, some_other_argument):
return some_other_argument
setattr(a, 'func', classmethod(func))
if __name__ == "__main__":
print(a.func)
print(a.func("asdf"))
返回以下輸出>
asdf
總結(jié)
以上是生活随笔為你收集整理的python类的动态方法是什么_如何在python中为类动态创建类方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python空集_玩转Python集合,
- 下一篇: python连接spark_python