Python-reflection, built-in methods

reflection

What is reflection

  • It refers to that the information of the object can be obtained "dynamically (see no coffin and no tears)" during the running of the program (that is, the attributes contained in the object can be obtained without knowledge)

How to achieve reflection?

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

    def say(self):
        print('<%s:%s>' %(self.name,self.age))

obj=People('辣白菜同学',18)

# 实现反射机制的步骤
# 1、先通过多dir:查看出某一个对象下可以.出哪些属性来
print(dir(obj))

# 2、可以通过字符串反射到真正的属性上,得到属性值
print(obj.__dict__[dir(obj)[-2]])

Use of four built-in functions

# 上述的方法有两个问题:
# 	一、不是所有的对象都能够访问__dict__属性,
# 	二、最好不要直接的去操作__dict__

# 通过字符串来操作属性值
# 1、hasattr()
print(hasattr(obj,'name'))
print(hasattr(obj,'x'))

# 2、getattr()
print(getattr(obj,'name'))

# 3、setattr()
setattr(obj,'name','EGON') # obj.name='EGON'
print(obj.name)

# 4、delattr()
delattr(obj,'name') # del obj.name
print(obj.__dict__)


res1=getattr(obj,'say') # obj.say # 对象调用函数返回绑定方法
res2=getattr(People,'say') # People.say # 类调用函数返回函数
print(res1)
print(res2)


# 反射案例
obj=10
if hasattr(obj,'x'):
    print(getattr(10,'x'))
else:
    print("对象10没有x属性")
    
print(getattr(obj,'x',None))

if hasattr(obj,'x'):
    setattr(obj,'x',111111111) # 10.x=11111
else:
    pass


class Ftp:
    def put(self):
        print('正在执行上传功能')

    def get(self):
        print('正在执行下载功能')

    def interactive(self):
        method=input(">>>: ").strip() # method='put'

        if hasattr(self,method):
            getattr(self,method)()
        else:
            print('输入的指令不存在')


obj=Ftp()
obj.interactive()

Built-in methods

What is a built-in method

  • Defined within the class, __starting with and __ending with the method
  • Features: will automatically trigger execution under certain circumstances

Why use built-in methods

  • To customize our class or object

How to use built-in methods

# __str__:在打印对象时会自动触发,然后将返回值(必须是字符串类型)当做本次打印的结果输出
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        # print('运行了...')
        return "<%s:%s>" %(self.name,self.age)


obj = People('辣白菜同学', 18)

# print(obj.__str__())
print(obj)  # <'辣白菜同学':18>

# obj1=int(10)
# print(obj1)

# __del__:在清理对象时触发,会先执行该方法
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.x = open('a.txt',mode='w')
        # self.x = 占据的是操作系统资源

    def __del__(self):
        # print('run...')
        # 发起系统调用,告诉操作系统回收相关的系统资源
        self.x.close()

obj = People('辣白菜同学', 18)
# del obj # obj.__del__()
print('============>')

Guess you like

Origin www.cnblogs.com/guanxiying/p/12708769.html