4.15 Reflection and built-in methods Reflection and built-in methods

Reflection and built-in methods

 

1. Reflection

1. What is reflection?

It refers to that the information of the object can be obtained "dynamically (without seeing the coffin and without tears)" while the program is running

2. Why use reflection

In the process of running the program, if we get an object that does not know what attributes are stored, if we want to manipulate its internal attributes, we can first get the attribute list of any class or object through the built-in function dir, which is all strings format

3. How to use the reflection mechanism

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) 

3.1 First through multiple dir: check which attributes can be found under a certain object

print(dir(obj))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say'] 

3.2 Can be reflected on the real attribute through the string to get the attribute value

print(obj.__dict__[dir(obj)[-2]])
辣白菜同学

3.3 Use of four built-in functions: Manipulating property values ​​through strings

# 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) <bound method People.say of <__main__.People object at 0x000000000268D9D0>> <function People.say at 0x00000000026FC430> 

Based on reflection, you can manipulate the properties of objects very flexibly, such as reflecting the results of user interaction to specific function execution

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() 

Second, the built-in method

1. What is the built-in method?

定义在类内部,以__开头并以__结尾的方法
特点:会在某种情况下自动触发执行

2. Why use the built-in method?

In order to customize our class or object

3. How to use the built-in method

# __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> 
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('============>') run... ============>

1. Reflection

1. What is reflection?

It refers to that the information of the object can be obtained "dynamically (without seeing the coffin and without tears)" while the program is running

2. Why use reflection

In the process of running the program, if we get an object that does not know what attributes are stored, if we want to manipulate its internal attributes, we can first get the attribute list of any class or object through the built-in function dir, which is all strings format

3. How to use the reflection mechanism

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) 

3.1 First through multiple dir: check which attributes can be found under a certain object

print(dir(obj))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say'] 

3.2 Can be reflected on the real attribute through the string to get the attribute value

print(obj.__dict__[dir(obj)[-2]])
辣白菜同学

3.3 Use of four built-in functions: Manipulating property values ​​through strings

# 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) <bound method People.say of <__main__.People object at 0x000000000268D9D0>> <function People.say at 0x00000000026FC430> 

Based on reflection, you can manipulate the properties of objects very flexibly, such as reflecting the results of user interaction to specific function execution

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() 

Second, the built-in method

1. What is the built-in method?

定义在类内部,以__开头并以__结尾的方法
特点:会在某种情况下自动触发执行

2. Why use the built-in method?

In order to customize our class or object

3. How to use the built-in method

# __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> 
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('============>') run... ============>

Guess you like

Origin www.cnblogs.com/haliluyafeng/p/12710153.html