python M3 面向对象

反射

反射很重要的原因,是可以实现一个动态的内存装配。通过字符串映射或修改程序运行时的状态、属性、方法, 主要有以下4方法

  1. hasattr(obj,name_str)判断一个object中有没有一个name字符串对应的方法或者属性
  2. getattr(obj, name_str) 根据字符串取获取object里对应方法的内存地址 并 调用by 加()
class Dog(object):

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

    def eat(self):
        print('%s is earting bum ' %(self.name))

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

# 引入反射,判断一个对象里是否有该方法
print(hasattr(d,choice))  # 判断choice的字符串是否在Dog类中方法
  1. setattr(obj, 'y', v) 等于 "x,y = v"重新赋值,

        3.1 动态增加新方法

def bark(self):
    print('%s is barking' %self)

class Dog(object):

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

    def eat(self):
        print('%s is earting bum ' %(self.name))


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

if hasattr(d,choice):
    func = getattr(d, choice)
    func("chenronghua")
else:
    setattr(d,choice,bark)  # 动态增加类的方法
    d.talk("vike")

  3.2 动态增加和修改属性

def bark(self):
    print('%s is barking' %self)

class Dog(object):

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

    def eat(self):
        print('%s is earting bum ' %(self.name))


d = Dog("Rory")
choice = input('>>:').strip()
if hasattr(d,choice):
    attr = getattr(d, choice)
    setattr(d, choice, "ronghua")  # 修改已有属性
else:
    #setattr(d,choice,bark)  # 动态增加类的方法
    setattr(d, choice, 22)   # 动态增加类的属性
    print(getattr(d,choice))

print(d.name)
  1. delattr(x,y) 删除
原文地址:https://www.cnblogs.com/lg100lg100/p/8253921.html