面向对象 反射方法

首先看一个例子

#在面向对象中一般情况下怎么去调属性
class
Student: def __init__(self, name, age): self.name = name self.age = age def run(self): print('=========>') class Teacher(Student): pass stu1 = Student('zhuyu', 19) print(stu1.name) #其本质就是 stu1.__dict__['name'] print(stu1.__dict__['name'])

# 反射:就是通过字符串的形式去操作属性

# 学好下面四个方法就好
hasattr(stu1, 'name')  # 就相当于Student.name,如果能找到name属性,就打印返回值True,报错了的话,就打印返回值False
getattr(stu1, 'run', None)  # 获取对象中的属性,没有的话会将第三个参数作为返回值
setattr(stu1, 'salary', 5000)  # 设置属性  第一个参数对象,第二个参数是属性,第三个参数是属性的值
print(stu1.__dict__)
delattr(stu1, 'salary')  # 删除一个属性
print(stu1.__dict__)

# 下面讲一个使用反射的一个例子

class Ftp:
    def __init__(self, ip, port):
        self.__ip = ip
        self.__port = port

    def get(self):
        print('%s执行get方法' % self.__ip)

    def put(self):
        print('%s执行put方法' % self.__ip)

    def run(self):
        while True:
            cmd = input('请输入命令>>:').strip()
            if cmd == 'q':break
            if hasattr(self, cmd):
                getattr(self, cmd)()
            else:
                print('命令不存在')


f1 = Ftp('1.1.1.1',8080)
f1.run()   
###可以通过反射来实现一个简单的c/s架构

猜你喜欢

转载自www.cnblogs.com/zhuchunyu/p/9445186.html