0
点赞
收藏
分享

微信扫一扫

Python(十六、反射)

编程练习生J 2021-09-27 阅读 35

1、什么是反射

> 通过字符串来操作类或者对象的属性

2、如何用

hasattr #查看属性是否存在,判断
getattr #得到属性的值,
setattr #更改属性的值
delattr #删除属性的值
  里面参数也就是属性要用字符串
class People:
    country='china'
    def __init__(self,name):
        self.name=name
    def eat(self):
        print('%s is eating '%self.name)
peo1=People('egon')

print(hasattr(peo1,'eat'))
print(hasattr(peo1,'uu'))#False

print(getattr(peo1,'name'))#得到一个值egon
print(getattr(People,'xou',None))#如果找不到该属性,第三个参数如果写则不报错,并且返回该参数,结果为None

setattr(peo1,'country','China')  #peo1.country='China'
print(peo1.country)

print(peo1.__dict__)
delattr(peo1,'name')#del peo1.name 删除属性name
print(peo1.__dict__)
class Ftp:
    def __init__(self,ip,port):
        self.ip=ip
        self.port=self

    def get(self):
        print('GET function')

    def put(self):
        print('PUT function')

    def run(self):
        while True:
            choice=input('输入你要操作的命令:').strip()
            # if hasattr(self,choice):
            #     m=getattr(self,choice,None)
            #     m()
            m=getattr(self,choice,None)#拿到输入的值,因为是字符串,
            if m:
                m()
            else:
                print('打印命令不存在')#找到属性则运行,就是反射


obj1=Ftp('11.4..5..6',222)
obj1.run()

重点

class Person(object):

    def __init__(self, name, gender, **kwargs):
        self.name = name
        self.gender = gender
        for key, value in kwargs.items():
            self.key = value
            # setattr(self, key, value)


p = Person('Bob', 'Male', age=18, course='Python')
print(p.age)
print(p.course)

print(dir(p))
# , 'gender', 'key', 'name'
# , 'age', 'course', 'gender', 'name'

"""
对比:self.key = value和setattr(self, key, value)

如果使用setattr(self, key, value)则相当于给p对象添加了age  和  course属性并赋值
如果使用self.key = value 相当于给p对象添加了属性就是"key"并且这个p.key永远都是最后一次遍历的值,此时就是Python,
如果把age=18, course='Python'换个顺序,则p.key就是18

有点类似js的["字符串"]形式添加属性
"""
举报

相关推荐

0 条评论