The GetAttr () function in Python is detailed:

Source: Internet
Author: User

The GetAttr () function in Python is detailed:

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

GetAttr (Object,name)

In fact, why not object.name and sometimes must use GetAttr (Object,name), mainly because the name here is likely to be a variable, we do not know what this name is,


Can only be obtained by GetAttr (Object,name).

Instance:

def info (object,spacing=10,collapse=1):

"" "Print methods and Doc strings.

Takes module, class, List, dictionary, or string. "" "


Methodlist=[method for method in Dir (object) if callable (GetAttr (Object,method))]

Processfunc=collapse and (Lambda s: ". Join (S.split ()))" or (lambda s:s)

print "\ r \ n". Join (["%s%s"% (method.ljust (spacing), Processfunc (str (getattr (object,method). __doc__))) for method in MethodList])


If __name__== ' __main__ ':

Print info.__doc__

Print info ([])


Theoretically, getattr can be used for tuples, but since tuples have no methods, no matter what property name you specify, GetAttr throws an exception. GetAttr () can be used for


Built-in data types can also be used for modules.

GetAttr () Three parameters, the first is an object, the second is a method, and the third is an optional default return value. Returns the default if the property or method specified by the second parameter is not found


Value.


GetAttr () as a distributor:


Import Statsout


def output (data,format= ' text '):

Output_function=getattr (statsout, ' output_%s '%format,statsout.output_text)

return Output_function (data)


The GetAttr () function in Python is detailed:

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.