python __getattr__ help

Posted by Stefanos Tux Zacharakis on Stack Overflow See other posts from Stack Overflow or by Stefanos Tux Zacharakis
Published on 2011-01-16T15:26:50Z Indexed on 2011/01/16 15:53 UTC
Read the original article Hit count: 364

Filed under:
|
|

Reading a Book, i came across this code...

# module person.py

class Person:

    def __init__(self, name, job=None, pay=0):
        self.name = name
        self.job  = job
        self.pay  = pay

    def lastName(self):
        return self.name.split()[-1]

    def giveRaise(self, percent):
        self.pay = int(self.pay *(1 + percent))

    def __str__(self):
        return "[Person: %s, %s]" % (self.name,self.pay)

class Manager():
    def __init__(self, name, pay):
        self.person = Person(name, "mgr", pay)

    def giveRaise(self, percent, bonus=.10):
        self.person.giveRaise(percent + bonus)

    def __getattr__(self, attr):
        return getattr(self.person, attr)

    def __str__(self):
        return str(self.person)

It does what I want it to do, but i do not understand the __getattr__ function in the Manager class. I know that it Delegates all other attributes from Person class. but I do not understand the way it works. for example why from Person class? as I do not explicitly tell it to. person(module is different than Person(class)

Any help is highly appreciated :)

© Stack Overflow or respective owner

Related posts about python

Related posts about python-datamodel