Day27- reflection and built-in method

I do not want to cheer and daily verse, I want to throw up.

Use breakpoints

You use the left mouse button, point to the front of the code, which is the number of rows back, there will be a red dot, red dot.

Then run debug, the program runs to the line and they will master card, then you can click Next Next, read the step by step. Useful, thief easy to use, easy to use bombs.

Issubclass and use of isinstance

This is also very simple.

Issubclass action is judged not a class is a subclass of another class. It is used as follows

class Foo:
    pass
class Bar(Foo):
    pass

class Tt(Bar):
    pass
print(issubclass(Bar,Tt))
print(issubclass(Bar,Foo))
print(issubclass(Tt,object))

False
True
True

Know like, do not BB

Isinstance action is to determine whether an object is an instance of class out

#判断第一个参数是不是第二个参数的对象,返回true或者false
class Foo:
    pass
class Tt():
    pass

f=Foo()
print(isinstance(f,Foo))
print(isinstance(f,Tt))

True
False

reflection

A user input a string, the string corresponding to the implementation of the method

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 a string # delattr (): method to delete an attribute or a string

The above methods are based on the string, you get a variety of ways by a variable, the variable value is a string, it is not a conventional manner by the operation performed.

hasattr () method

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


p=Foo()
cmd='speak'
if hasattr(p,cmd):
    func=getattr(p,cmd)
    func()
else:
    print('该命令不存在')

speak

setattr () method

#动态的往对象中放方法


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


p=Foo()
def test(a):
    print(a)
print(p.__dict__)
key='name'
value=test
setattr(p,key,value)
print(p.__dict__)
p.name('nick')

{}
{'name': <function test at 0x000001B1F02DF048>}
nick

delattr () method

#动态的删除属性.
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('请输入要删除的属性:')
print(p.__dict__)
delattr(p,a)
print(p.__dict__)

Enter the property to delete: Age
{ 'name': 'LQZ', 'Age': 18 is, 'Sex': 'MALE'}
{ 'name': 'LQZ', 'Sex': 'MALE'}

Built-in method

__init__ method before we learned that he is the way we will automatically invoked when an object is instantiated, today, speaking about several other built-in method, which begins with __ and __ method ends are built-in method , also known as magic methods, you can speak during the interview about the magic method, Zhibuding bar interviewer to force the whole Mongolia.

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

__repr__: str with 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)

[nick]

When you use the print, the class will be executed inside __str__ method, and the method before returning, in fact, you all have to call this method at the time of printing. Of course, if you get rid of this method it is to print out the address of the object.

setattr,delattr,getattr(重要)

These three points are called the intercept method

If you go to fetch the object attributes, 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')
print(f.age)
print(f.__dict__)

yyyyy
XXXX
you sucker ah, without this field
{}

I pinch Cock count, you have to force the ignorant, yes indeed call that does not exist when the property is not called getattr method. Well, since this call to prove that the object is there, certainly no method name, so why start the assignment clearly Nick, did not it? In the beginning of the assignment, the object which is no name for this property, then when you assign property that does not exist, it will call setattr method, only this time on the implementation of this method is over. And no assignment. understand?

Then print f.age, age have it, do not, so go getattr method.

The method of Example 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')
print(f.__dict__)
del f.name
print(f.__dict__)

{'name': 'nick'}
zzzzz
{'name': 'nick'}

I believe there should be careful of sand sculptures have been found setattr I commented out the method, as long as there is an assignment situation, but if it does not exist prior to this property, they will call this method and assign this operation will fail, so I am his mother delattr no way to demonstrate this method! So I can only put it annotated.

When the operation is called del delattr method, in fact, we see deleted, it is carried out in this method there. But here we just print zzzzz, not deleted, so there is still dict name of this property.

Non-conventional methods take a value dictionaries

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

di=Mydict(name='lqz',age=18)
print(di['name'])
print(di.name)
di.sex='male'
print(di.sex)
di['sex']='male'
print(di.sex)

lqz
lqz
male
male

We see that, Mydict inherited the dict class, and automatically calls the parent class init method to instantiate an object in time, which generated a dictionary, then we pass di [ 'name'] and di.name way can take the value of the name, because the name of the call, I found no, go back to perform getattr method, then you understand.

#__item__系列  对象通过[] 中括号取值,赋值,删除值的时候,会调用
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'])

As long as carry out his things through the brackets, it will call getitem or setitem or delitem. Bb a few. .

#__call__   对象加括号会调用它
class Foo:
    def __call__(self):
        print('xxxx')

f=Foo()
f()

understand?

#__enter__和__exit__
#上下文管理器,本质原来
# with open() as f:
#     pass

This I do not understand, say tomorrow

Oh, today the talk is too serious.

Guess you like

Origin www.cnblogs.com/chanyuli/p/11449481.html