pyton3 反射相關的一些操作

# -*- coding:utf-8 -*-
# Author: Evan Mi


class Dog(object):

    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating ... %s' % (self.name, food))


def buck(self):
    print('%s is bucking' % self.name)


d = Dog('jack')
choice = input('>>: ').strip()
# 判斷是否有屬性或方法
print(hasattr(d, choice))
# 獲得對象的屬性或方法(如果是方法,後面加括號後調用)
func = getattr(d, choice)
func('some')
print(getattr(d, 'name'))
# 給對象添加一個方法或屬性,方法或屬性的名字自己起
setattr(d, 'bb', buck)
setattr(d, 'age', 22)
print(d.age)
d.bb(d)  # 動態增加的方法不會自動穿self,需要自己手動去傳
# 刪除對象的屬性
delattr(d, 'name')
print(hasattr(d, 'name'))



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章