Python Class: Object-oriented advanced programming __getattr__

Source: Internet
Author: User

Website Explanation:

  • object.__getattr__(Self, name)

  • Called when an attribute lookup had not found the attribute in the usual places (i.e. it's not a instance attribute nor Is it found in the class tree forself).nameis the attribute name.This method should return the(computed) attribute valueorRaise anAttributeErrorException.


When we want to call something in class, and the class does not, the interpreter is bound to error, stop running, then someone thought: really trouble, every time to re-execute again, if I call the wrong content, the program can put me this error when the default program execution, and do not stop my program to run just fine. So, in order to solve this kind of problem, came out __getattr__ this function.

I guess, because the difficulty of solving the program is also a requirement.


See the error call without __getattr:

#!/usr/bin/python

#-*-Coding:utf-8-*-


Class Student (object):

def __init__ (self):

Self.name = ' Michael '


s = Student ()

Print S.name

Print S.score #Class中没有这个属性

Look, the first print executes normally, and the second one does not have this attribute in class, so it is an error.


Look again, the class with __getattr__:

#!/usr/bin/python

#-*-Coding:utf-8-*-


Class Student (object):

def __init__ (self):

Self.name = ' Michael '


def __getattr__ (self, Other):

If other== ' score ':

Return 99

s = Student ()

Print S.name

Print S.score #Class中没有这个属性

Print S.gg #Class中没有这个属性


Look again, print's score and GG are not defined in class, but both have outputs. Because the program to find __getattr__, just well defined a character to determine if other== ' score ':, so the output of 99, and GG A word did not mention, the default output is None. is not the feeling after the code program when no longer worry about the program to stop running.

Python Class: Object-oriented advanced programming __getattr__

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.