Reflection and built-in method

Reflection and built-in method

A reflective

hasattr (): determining whether an attribute in an object, returns True or Flase

class Foo:
    def run(self):
        print('run')
    def speak(self)
        print('speak')
        
p = Foo()

cmd = input('请输入命令:')
if hasattr(p,cmd):
    print('在')
else:
    print('不在')

getattr (): get property methods or string, if acquired, it will return the corresponding property or method

class Foo:
    def run(self):
        print('run')
    def speak(self)
        print('speak')
        
p = Foo()
cmd = input('请输入命令:')
if hasattr(p,cmd):
    run = getattr(p,cmd)
    run()
else:
    print('该命令不存在')

setattr () : method to set properties or string

#通过用户输入key和value往对象中赋值
class Foo:
    def run(self):
        print('run')
    def speak(self)
        print('speak')
        
p = Foo()
key = input('请输入key:')  #与用户交互,输入age
value = input('请输入value:')  #与用户交互,输入18
setattr(p,key,value)
print(p.age)
-----------------------------------------
18
#动态的往对象中放方法
class Foo:
    def run(self):
        print('run')
    def speak(self)
        print('speak')
    def test(a):
        print(a)
p = Foo()        
print(p.__dict__)  #{} 
setattr(p,'test'test)
print(p.__dict__) #{'test': <function test at 0x0000024A2D41D400>}
p.test(0)
---------------------------------------
0

delattr (): to delete an attribute or a method by a string

#动态删除p中属性为变量a的属性
class Foo:
    def run(self):
        print('run')
    def speak(self)
        print('speak')
    def test(a):
        print(a)
p = Foo()
p.name = 'yjy'
p.age = 20
p.sex = 'female'
a = input('请输入要删除的属性:')  #age
print(p.__dict__)  #{'test': <function test at 0x0000020532F1D400>, 'name': 'yjy', 'age': 20, 'sex': 'female'}
delattr(p,a)
print(p.dict__)   #{'test': <function test at 0x0000020532F1D400>, 'name': 'yjy', 'sex': 'female'}

Built-in method

__str__If you do not rewrite __str__print print will print out the memory address, if the rewrite will print out what you want

class Foo:
    def __init__(self,name);
    self.name = name
    def __str__(self) 
    return '['+self.name+']'

f = Foo('yjy')
print(f.__str__())   #[yjy]   此时和print(f)一样

-------
#再举个例子
-------
l = [1,2,3]
#本质也是调用list的__str__方法
  • Point intercept method

__getattr__: If you go to take the object attributes, once to get any, will enter into__getattr__

__setattr__: If you assign attributes to object once to get any, will enter__setattr__

__delattr__: If the object attribute is removed, once to get any, will enter__delattr__

class Foo:
    def __init__(self,name):
        self.name=name
    def __getattr__(self, item):
        return '没有这个字段'
    def __setattr__(self, key, value):
        print('yyyyy')
    def __delattr__(self, item):
        print('zzzzz')

f=Foo('YJY')   #我们要给他赋值,没有取到打印yyyyy
print(f.name)  #我们获取name这个属性,没有取到则打印’没有这个字段‘
del f.name   #我们删除name这个属性,没有取到,则答应’zzzzz'

__item__Time series by an object [] values, assign, remove the value of calls

#写一个类继承字典,让它可以 . 取值,可以中括号取值
class Mydict(dict):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
    def __getattr__(self, item):    
        # print(item)
        return self[item]
    def __setattr__(self, key, value):
        self[key]=value

        
# print(di['name'])
# print(di.name)
# di.sex=19
# print(di.sex)
di['sex']='male'
print(di.sex)
class Foo:
    def __init__(self, name):
        self.name = name
    def __getitem__(self, item):
        name=getattr(self,item)
        # print(name)
        return name
        # return self.__dict__[item]
    def __setitem__(self, key, value):
        print('obj[key]=lqz赋值时,执行我')
        self.__dict__[key] = value
    def __delitem__(self, key):
        print('del obj[key]时,执行我')
        self.__dict__.pop(key)

f=Foo('nick')
print(f['name'])   #nick

__call__: Object brackets will call it

class Foo:
    def __call__(self):
        print('hfsdhfsdh')
      
f = Foo()
f()   #hfsdhfsdh
  • Context manager, essentially __enter__, and__exit__
with open() as f:
    pass

Guess you like

Origin www.cnblogs.com/yanjiayi098-001/p/11449121.html