Python _ setattr _, _ getattr _, _ delattr _, and _ call _ examples

Source: Internet
Author: User
This article mainly introduces the usage examples of Python _ setattr _, _ getattr _, _ delattr _, and _ call, this article explains these magic methods separately. For more information, see Getattr

The 'getattr' function is a built-in function and can be obtained by function name.

The code is as follows:


Value = obj. attribute
Value = getattr (obj, "attribute ")


Use 'getattr 'to implement the factory mode

The code is as follows:


# A module supports printing in html, text, xml, and other formats. different functions are called to implement output in several formats based on the input formate parameters.

Import statsout

Def output (data, format = "text "):
Output_function = getattr (statsout, "output _ % s" % format)
Return output_function (data)

_ Call __

The '_ call _' method is used to call the instance itself:

The code is as follows:


Class storage (dict ):
# _ Call _ method used to call the instance itself
# Achieve () call results
Def _ call _ (self, key ):
Try:
Return self [key]
Failed T KeyError, k:
Return None

S = storage ()
S ['key'] = 'value'
Print s (key) # call __

_ Getattr __

When reading an attribute from an object, you must first search for the attribute from self. _ dicts _ and then search for it from _ getattr.

The code is as follows:


Class A (object ):
Def _ init _ (self ):
Self. name = 'from _ dicts __: zdy'

Def _ getattr _ (self, item ):
If item = 'name ':
Return 'from _ getattr __: zdy'
Elif item = 'age ':
Return 26

A = ()
Print a. name # obtained from _ dict _
Print a. age # obtained from _ getattr _

_ Setattr __

The '_ setattr _' function is used to set attributes of an object. you can use the _ setattr _ function in the object to set attributes:

The code is as follows:


Class A (object ):
Def _ setattr _ (self, * args, ** kwargs ):
Print 'Call func set attr'
Return object. _ setattr _ (self, * args, ** kwargs)

_ Delattr __

The '_ delattr _' function is used to delete object attributes:

The code is as follows:


Class A (object ):
Def _ delattr _ (self, * args, ** kwargs ):
Print 'Call func del attr'
Return object. _ delattr _ (self, * args, ** kwargs)

Example

Complete example can refer to Weibo API: http://github.liaoxuefeng.com/sinaweibopy/

The code is as follows:


Class _ Executable (object ):

Def _ init _ (self, client, method, path ):
Self. _ client = client
Self. _ method = method
Self. _ path = path
#__ Call _ function implementation _ Executable function object is callable
Def _ call _ (self, ** kw ):
Method = _ METHOD_MAP [self. _ method]
If method = _ HTTP_POST and 'Pic 'in kw:
Method = _ HTTP_UPLOAD
Return _ http_call ('% s. json' % (self. _ client. api_url, self. _ path), method, self. _ client. access_token, ** kw)

Def _ str _ (self ):
Return '_ Executable (% s)' % (self. _ method, self. _ path)

_ Repr _ = _ str __

Class _ Callable (object ):

Def _ init _ (self, client, name ):
Self. _ client = client
Self. _ name = name

Def _ getattr _ (self, attr ):
If attr = 'get ':
# Initialize the _ Executable object and call the _ init _ function.
Return _ Executable (self. _ client, 'get', self. _ name)
If attr = 'Post ':
Return _ Executable (self. _ client, 'post', self. _ name)
Name = '% s/% s' % (self. _ name, attr)
Return _ Callable (self. _ client, name)

Def _ str _ (self ):
Return '_ Callable (% s)' % self. _ name

_ Repr _ = _ str __

The following code snippet exists in the source code:

The code is as follows:


Class APIClient (object ):
'''
API client using synchronized invocation.
'''
...

Def _ getattr _ (self, attr ):
If '_' in attr:
Return getattr (self. get, attr)
Return _ Callable (self, attr)

Therefore, add the initialization object and call a function as follows:

The code is as follows:


Client = APIClient (...)
# The _ getattr _ function is called to call the _ call _ function.
Client. something. get ()

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.