12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

every attribute in the instance. It uses the _ _dict_ _ attribute namespace dictionaryto build up the list of “name=value” pairs for each attribute in the classinstance and the built-in _ _name_ _ of an instance’s built-in _ _class_ _ to determinethe class name. Because the print statement triggers _ _str_ _, this class’result is the custom print format displayed for all instances that derive from theclass. It’s a generic tool.• Person records general information about people, and provides two processingmethods to use and change instance object state information; it also inherits thecustom print format logic from its superclass. A person object has two attributesand two methods managed by this class.• Employee is a customization of Person that inherits the last-name extraction andcustom print format, but adds a new method for giving a raise, and redefines thebirthday operation to customize it (apparently, employees age faster than otherpeople). Notice how the superclass constructor is invoked manually; we need torun the superclass version above in order to fill out the name and age.As you study this module’s code, you’ll see that each instance has its own state information.Notice how inheritance is used to mix in and customize behavior, and howoperator overloading is used to initialize and print instances:# person.pyclass GenericDisplay:def gatherAttrs(self):attrs = '\n'for key in self._ _dict_ _:attrs += '\t%s=%s\n' % (key, self._ _dict_ _[key])return attrsdef _ _str_ _(self):return '' % (self._ _class_ _._ _name_ _, self.gatherAttrs( ))class Person(GenericDisplay):def _ _init_ _(self, name, age):self.name = nameself.age = agedef lastName(self):return self.name.split( )[-1]def birthDay(self):self.age += 1class Employee(Person):def _ _init_ _(self, name, age, job=None, pay=0):Person._ _init_ _(self, name, age)self.job = jobself.pay = paydef birthDay(self):self.age += 2def giveRaise(self, percent):self.pay *= (1.0 + percent)A More Realistic Example | 513

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!