亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:在運行時更改方法和屬性

Python:在運行時更改方法和屬性

慕娘9325324 2019-12-10 09:35:29
我希望在Python中創建一個可以添加和刪除屬性和方法的類。我該如何完成?哦,請不要問為什么。
查看完整描述

3 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

我希望在Python中創建一個可以添加和刪除屬性和方法的類。


import types


class SpecialClass(object):

    @classmethod

    def removeVariable(cls, name):

        return delattr(cls, name)


    @classmethod

    def addMethod(cls, func):

        return setattr(cls, func.__name__, types.MethodType(func, cls))


def hello(self, n):

    print n


instance = SpecialClass()

SpecialClass.addMethod(hello)


>>> SpecialClass.hello(5)

5


>>> instance.hello(6)

6


>>> SpecialClass.removeVariable("hello")


>>> instance.hello(7)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: 'SpecialClass' object has no attribute 'hello'


>>> SpecialClass.hello(8)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: type object 'SpecialClass' has no attribute 'hello'


查看完整回答
反對 回復 2019-12-10
  • 3 回答
  • 0 關注
  • 509 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號