8.python Face Object Part.6 (reflective &__call__,__setattr__,__delattr__,__getattr__)

Source: Internet
Author: User

I. What is reflection?

Reflection, also known as introspection, refers to the ability of the program itself to access, detect, and modify "itself", state or behavior.


Two. How does python embody this reflection mechanism?

Using strings to manipulate object-related properties, in Python, everything is object, and all places can be reflected.

Within Python, there are four functions that implement reflection (introspection), and these four functions can be applied to any class and object (because the class itself is also an Object!). )


1.hasattr (OBJECT,STR) is used to detect whether a string corresponds to a method or property in an object.

For example:

L1 = []

Print hasattr (L1, "append")

True

#如果一个对象中有以这个字符串命名的属性或者方法, return true directly, or return false.

#在一个列表中是没有keys方法的.

L1 = []

Print hasattr (L1, "keys")

False


2.getattr (OBJECT,STR,DEFAULTSTR) takes a string to get the property or method of an object, if the specified property is not found or the method throws an exception by default.

L1 = [A]

Print getattr (L1, "pop")

#获取l1这个对象的pop方法, the Pop method is acquired, followed by a parenthesis.

<built-in method Pop of list object at 0x1076097a0>

Print getattr (L1, "Pop") ()


When you want to find a property or method in an object that does not exist and does not want to throw an exception directly, use the third parameter of GetAttr, which can specify what the value is returned if the specified property is not found or the method returns by default.

L1 = [A]

Print getattr (L1, "aaaaaaa", "I dont know")

# Look for a method named Aaaaaaa in the L1 object and return an i dont know if not found.

I dont know


3.setattr (Object,key,value) creates a new property for an object by means of a string, and it can also modify the original properties of an object.

Class Test (object):

def __init__ (self):

Self.test = "Test"

test1 = Test ()

Print Test1.test

Test

SetAttr (test1, "test", "Ayumi")

# Modify the properties in an object

Print Test1.test

Ayumi

SetAttr (test1, "AAA", "BBB")

# Add an attribute to an object.

Print TEST1.AAA

Bbb



4.delattr (OBJECT,STR) Removes a property or method from an object by a string, and an error occurs when the deleted attribute does not exist.


Three. __call__,__setattr__,__delattr__,__getattr__

    1. The __call__ method is used for calls to the object itself.

When an object is appended with () parentheses to invoke itself, it triggers its own __call__ method, and the code below the __call__ method is executed back.

class Person (object):

def __init__ (self,name,age):

Self.name = Name

Self.age = Age

def __call__ (self, *args, **kwargs):

Print "performed the __call__ method"

Print Self.name

Print Self.age

Ayumi = Person ("Hamasakiayumi", "38")

#ayumi is now an object that adds () parentheses directly behind the object and executes the code below the __call__ method.

Ayumi ()

Output:

Implemented the __call__ method

Hamasakiayumi

38


2.__getattr__ when the property to be called does not exist, the following method is triggered __getattr__.

class Person (object):

def __init__ (self,name,age):

Self.name = Name

Self.age = Age

def __call__ (self, *args, **kwargs):

Print "performed the __call__ method"

Print Self.name

Print Self.age

def __getattr__ (self, item):

Print "This method or property does not exist"

# when the specified property or method is not found, the __getattr__ method is triggered and the print "This method or property does not exist"

Ayumi = Person ("Hamasakiayumi", "38")

Ayumi.assasasaas

Output:

This method or property does not exist


3.__setattr__ when a property of an object or class is modified, the __setattr__ method is triggered, which itself is used to set properties in the object.

class Person (object):

def __init__ (self,name,age):

Self.name = Name

Self.age = Age

def __call__ (self, *args, **kwargs):

Print "performed the __call__ method"

Print Self.name

Print Self.age

def __getattr__ (self, item):

Print Item

Print "This method or property does not exist"

#def __setattr__ (self, *args, **kwargs):

#print "Triggering __setattr__ method"

#return object. __SETATTR__ (Self,*args,**kwargs)

def __setattr__ (self, Key, value):

Print "Trigger __setattr__ method"

# Self.key=value #这就无限递归了, you think about it

Self.__dict__[key]=value #应该使用它

In fact, the above two ways to implement the functions are the same, the following is easier to understand the wording, directly modify the __dict__ this property dictionary.


Ayumi = Person ("Hamasakiayumi", "38")

Ayumi.song = "Fly High"

#为一个对象增加一个属性, the __setattr__ method was executed.

Print Ayumi.song

Output:

Trigger __setattr__ method

Trigger __setattr__ method

Trigger __setattr__ method

Fly high



4.__delattr__ when you delete an attribute in an object, or a method, the __delattr__ method is triggered.

class Person (object):

def __init__ (self,name,age):

Self.name = Name

Self.age = Age

def __call__ (self, *args, **kwargs):

Print "performed the __call__ method"

Print Self.name

Print Self.age

def __getattr__ (self, item):

Print Item

Print "This method or property does not exist"

def __setattr__ (self, *args, **kwargs):

Print "Trigger __setattr__ method"

Return object. __SETATTR__ (Self,*args,**kwargs)

# def __delattr__ (self, *args, **kwargs):

# print ' Call func del attr '

# return object.__delattr__ (self, *args, **kwargs)

# This notation is inherited from the __delattr__ method implemented in the new class.

def __delattr__ (self, item): #当使用del关键词删除一个属性或者方法的时候, __delattr__ the following code

Print "Trigger __delattr__ method" will be triggered.

Self.__dict__.pop (item) # This is the delete action.

Ayumi = Person ("Hamasakiayumi", "38")


Attention!! __call__,__setattr__,__delattr__,__getattr__ these four methods, the system has been defined by default, when there are special needs, it is necessary to define their own.



This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1917254

8.python Face Object Part.6 (reflective &__call__,__setattr__,__delattr__,__getattr__)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.