Python getattr function Use method GetAttr Implement Factory mode

Source: Internet
Author: User
Looked at the doc of the function itself
Copy CodeThe code is as follows:


GetAttr (object, name[, default]), value

Get A named attribute from an object; GetAttr (x, ' Y ') is equivalent to x.y.
When a default argument is given, it's returned when the attribute doesn ' t
Exist Without it, an exception was raised in the case.

The explanation is very abstract and tells me that this function acts as a

Object.name

Try it. GetAttr (Object,name) is indeed the same function as object.name. It's just that you can use name as a variable to deal with the example of the book. This function is well illustrated by using the GetAttr to easily implement the factory pattern.

Example: A module supports printing in HTML, text, XML and other formats, and calls different functions to implement output in several formats, depending on the formate parameter passed in.

Copy the Code code as follows:


Import Statsout
def output (data, format= "text"):
Output_function = GetAttr (statsout, "output_%s"%format)
return Output_function (data)
[Code]
In this example, different methods of the Statsout module can be called depending on the format parameter of the incoming output function (implementation of output_%s with the formatted string)

Return the object of this method can be used directly if you want to add a new format only need to write a new method function in the module when calling the output function, you can use a different format output

It's really convenient.


In order to deepen the understanding of the GetAttr function, reprint an English explanation

Python's GetAttr function is used to fetch an attribute from an object, using a string object instead of a identifier to Identify the attribute. In other words, the following and statements are equivalent:

[Code]
Value = Obj.attribute
Value = GetAttr (obj, "attribute")
If the attribute exists, the corresponding value is returned. If The attribute does not exist, you get a Attributeerror exception instead.

The GetAttr function can be used in any object, supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects.

Path = GetAttr (sys, "path")
Doc = GetAttr (len, "__doc__")
The GetAttr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attrib Utes and methods:

result = Obj.method (args)

Func = getattr (obj, "method")
result = Func (args)
Or, in one line:

result = GetAttr (obj, "method") (args)
Calling both GetAttr and the method on the same line can make it hard to handle exceptions. To avoid confusing attributeerror exceptions raised by GetAttr with similar exceptions raised inside the method, you can u Se the following pattern:

Try
Func = getattr (obj, "method")
Except Attributeerror:
... deal with missing method ...
Else
result = Func (args)
The function takes an optional default value, which is used if the attribute doesn ' t exist. The following example only calls the method if it exists:

Func = getattr (obj, "method", None)
If Func:
Func (args)
Here's a variation, which checks that's the attribute is indeed a callable object before calling it.

Func = getattr (obj, "method", None)
If callable (func):
Func (args)

  • 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.