Python __setattr__, __getattr__, __delattr__, __call__ usage examples _python

Source: Internet
Author: User

GetAttr

The ' getattr ' function belongs to the built-in function, and can be obtained by using the function name

Copy Code code as follows:

Value = Obj.attribute
Value = GetAttr (obj, "attribute")

Use ' getattr ' to implement Factory mode
Copy Code code as follows:

#一个模块支持html, text, XML and other formats of printing, according to the incoming formate parameters of different, call different functions to achieve the output of several formats

Import Statsout

def output (data, format= "text"):
Output_function = GetAttr (statsout, "output_%s"%format)
return Output_function (data)

__call__

The ' __call__ ' method is used for calls to the instance itself:

Copy Code code as follows:

Class Storage (DICT):
# __call__ method for invocation of instance itself
Effect of #达到 () call
def __call__ (self, key):
Try
return Self[key]
Except Keyerror, K:
Return None

s = Storage ()
s[' key ' = ' value '
Print S (key) #调用__call__

__getattr__

When you read a property from an object, you first need to search for the attribute from the self.__dicts__ and then look for it from the __getattr__.

Copy Code code 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 = A ()
Print A.name # obtained from __dict__
Print A.age # obtained from __getattr__

__setattr__

The ' __setattr__ ' function is used to set the properties of an object, using the __SETATTR__ function in object to set the property:

Copy Code code 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 an object's properties:

Copy Code code as follows:

Class A (object):
def __delattr__ (self, *args, **kwargs):
print ' Call func del attr '
Return object.__delattr__ (self, *args, **kwargs)

Example

Complete examples can refer to Weibo api:http://github.liaoxuefeng.com/sinaweibopy/

Copy Code code as follows:

Class _executable (object):

def __init__ (self, client, method, path):
self._client = Client
Self._method = method
Self._path = Path
#__call__函数实现_Executable函数对象为可调用的
def __call__ (self, **kw):
method = _method_map[self._method]
If Method==_http_post and ' pic ' in kw:
method = _http_upload
Return _http_call ('%s%s.json '% (Self._client.api_url, Self._path), method, Self._client.access_token, **kw)

def __str__ (self):
Return ' _executable (%s%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 ':
#初始化_Executable对象, 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__

In the source code, there are the following snippets:

Copy Code code 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)

So, join us to initialize the object and call a function as follows:

Copy Code code as follows:

Client = Apiclient (...)
#会调用__getattr__函数, thus calling the __call__ function
Client.something.get ()

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.