Python3 中类的反射

1.针对类中方法的反射

#  反射的使用
class Dog(object):

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

    def eat(self):
        print('%s is eating...'%self.name)
def bulk(self):
    print('%s is yaling...'%self.name)

d = Dog('wt')
choice = input('>>:').strip()

if hasattr(d,choice):
    func = getattr(d,choice)
    func()
else:
    setattr(d,choice,bulk)
    func = getattr(d, choice)  
    func(d)

2.针对类成员变量的使用

#  反射的使用
class Dog(object):

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

    def eat(self):
        print('%s is eating...'%self.name)
def bulk(self):
    print('%s is yaling...'%self.name)

d = Dog('wt')
choice = input('>>:').strip()

if hasattr(d,choice):
    print(getattr(d,choice))
else:
    setattr(d,choice,'hjc')
    print(getattr(d,choice))

总的来说就是判断是否有输入的choice,若有则进行输出,若没有则进行赋值或者替换。

posted @ 2017-03-22 13:28  KaShing  阅读(430)  评论(0编辑  收藏  举报