issubclass and the isinstance, reflection, built-in method

Advanced Object-Oriented

A, issubclass and isinstance

1.1 issubclass

issubclass()

Effect: for determining a first class in brackets is not a subclass of the second class, returns a value of True or False.

E.g:

class A:
    pass
class B(A):
    pass
class C:
    pass

print(issubclass(B,A))  # True
print(issubclass(C,A))  # False

1.2 isinstance

isinstance()

Action: used to determine the first parameter is not the second brackets object parameters, return results to True or False.

E.g:

class A:
    pass
class B:
    pass

a = A()
print(isinstance(a,A))  # True
print(isinstance(a,B))  # False

Second, reflection

2.1 What is the reflection

Judged by a string, get, set, delete objects (including classes, modules, etc., are all subject) attributes or methods.

2.2 four object properties can be built-in functions and operation methods of the string

Four functions in parentheses first argument is an object

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

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

setattr (): method to set properties or string

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

2.2.1 hasattr ()

Determining whether an attribute in an object, the object is the first parameter, the second parameter is a property that returns True or False

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

p=Foo()
cmd=input('请输入命令:')
if hasattr(p,cmd):  # 先判断属性cmd是否在对象p中
    run=getattr(p,cmd)   # 如果输入run,该属性或方法就在对象p中,就会返回,加括号就可以调用
    run()
else:
    print('该命令不存在')  # 输入的属性不在对象中的话,就执行这步

2.2.2 getattr()

By acquiring a string property or method, if acquired, it will return the corresponding property or method, the use of the above code has been written

2.2.3 setattr()

1, through the user input key and the value assigned to the object

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)  # 将{'ag':'18'}赋值给对象p
print(p.age)  # 18

2, a dynamic method to put the object

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

p=Foo()
def test(a):
    print(a)
print(p.__dict__)  # {}
setattr(p,'test',test)  
print(p.__dict__)  # {'test': <function test at 0x000001DF69C81E18>}
p.test(0) # 0

2.3.4 delattr()

Dynamic delete objects p variable attributes of a property

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

p=Foo()
p.name='lqz'
p.age=18
p.sex='male'
a=input('请输入要删除的属性:')  # 输入sex
print(p.__dict__)  # {'name': 'lqz', 'age': 18, 'sex': 'male'}
delattr(p,a)   #把属性sex删除
print(p.__dict__)  # {'name': 'lqz', 'age': 18}
# 直接p.a是不对的
# del p.a  这个会报错

Third, the built-in method

Before learned__init__

3.1 __str__and__repr__

1 __str__: If you do not rewrite __str__, print print will print out the memory address, if rewritten, it will print out what you want

2 __repr__: and __str__similar, direct write the variable name in an interactive command, execute__repr__

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

f=Foo('nick')
print(f.__str__())  # [nick]
print(f)     #相当于上面那句  # [nick]
l=[1,2,3]
#本质也是已经调用list的__str__方法
print(l)

3.2 point intercept method: __setattr__, __delattr__,__getattr__

If the object is to acquire property, once to get any, will enter into__getattr__

If you assign attributes to objects, once to get any, will enter into__setattr__

If the attribute deleted object will enter__delattr__

class Foo:
    def __init__(self,name):
        self.name=name
    def __getattr__(self, item):
        # print('xxxx')
        return '你傻逼啊,没有这个字段'
    def __setattr__(self, key, value):
        print('yyyyy')
    def __delattr__(self, item):
        print('zzzzz')
f=Foo('nick')  # 给对象f赋值属性,对象中没有这个属性,进入到__setattr__方法  # yyyyy
print(f.name)  # 获取name属性,对象中没有属性,进入__getattr__方法  # 你傻逼啊,没有这个字段
print(f.age)   # 没有age属性,进入__getattr__方法  # 你傻逼啊,没有这个字段
print(f.__dict__)   # {}
print(f.name)  # 没有name属性,进入__getattr__方法  # 你傻逼啊,没有这个字段
f.sex='male'   # 给对象f赋值属性,对象中没有sex这个属性,进入到__setattr__方法  # yyyyy

del f.name    # 删除对象name属性,对象中没有这个属性,进入__delattr__方法  # zzzzz
print(f.__dict__)  # {}

3.3 __item__

Objects by [] brackets value, assignment, delete worth when it will call the __item__method

class Foo:
    def __init__(self, name):
        self.name = name
    def __getitem__(self, item):
        name=getattr(self,item)
        # print(name)
        # print(self.__dict__[item])
        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'])

3.4 __call__

Object brackets will call it

class Foo:
    def __call__(self):
        print('xxxx')

f=Foo()
f()  # xxxx

3.5 __enter__and__exit__

with nature management context

class Open:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')
        # return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代码块执行完毕时执行我啊')


with Open('a.txt') as f:
    print('=====>执行代码块')
    # print(f,f.name)
出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量
=====>执行代码块
with中代码块执行完毕时执行我啊
  • exit three parameters () represent the exception type, and outlier traceability information, with exception code block appears the statement, the code can not be performed with the
class Open:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代码块执行完毕时执行我啊')
        print(exc_type)
        print(exc_val)
        print(exc_tb)


try:
    with Open('a.txt') as f:
        print('=====>执行代码块')
        raise AttributeError('***着火啦,救火啊***')
except Exception as e:
    print(e)

With statements appear, __enter__ object is triggered, the return value is assigned to a variable declared as
=====> code block is executed
with execution when I finished the block ah
<class 'AttributeError'>
on fire, fire ah
<traceback object at 0x1065f1f88>
on fire, fire ah

  • If __exit () return value is True, then the exception will be emptied, as if got nothing happened, after the sentence with normal execution
class Open:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代码块执行完毕时执行我啊')
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        return True


with Open('a.txt') as f:
    print('=====>执行代码块')
    raise AttributeError('***着火啦,救火啊***')
print('0' * 100)  #------------------------------->会执行

With statements appear, __enter__ object is triggered, the return value is assigned to a variable declared as
=====> code block is executed
with execution when I finished the block ah
<class 'AttributeError'>
on fire, fire ah
<the traceback calls out AT 0x1062ab048 Object>
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11449534.html