python_面向对象——反射

1.反射

  四个方法:getattr()  获取

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person('wdc',22)

a = getattr(p,'name')   #获取对象p的字符串为“name”的方法
print(a)

       hasattr()  判断

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person('wdc',22)
if hasattr(p,'name'):   #反射:判断对象p中是否有字符串为“name”的方法。
    print('')
else:
    print('没有')

       setattr()  赋值

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person('wdc',22)
setattr(p,'sex','Female')   #给对象p创建一个为“sex”的属性,并赋值为“Female”
print(p.sex)

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

def talk(self):
    print('{} is speaking ...'.format(self.name))


p = Person('wdc',22)
# 给类绑定一个新的方法
setattr(Person,'speak',talk)    #为类Person添加名字为“speak”的方法,并把函数talk赋值给speak方法
p.speak()

       delattr()  删除

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person('wdc',22)
print(p.age)
delattr(p,'age')    #删除对象p的名字叫做“age ”的方法
print(p.age)

原文地址:https://www.cnblogs.com/wangdianchao/p/11985979.html