[Chicago] Frame Hacks Lightning Talk Code
Feihong Hsu
hsu.feihong at yahoo.com
Fri Nov 16 17:31:24 CET 2007
Because I didn't get to type it out in front of everyone, I'm posting the example where I use frame manipulation to generate properties on a class.
Warning: The following code may crash your computer if you allow a strange Asian man with a unique electromagnetic aura to type it in using your keyboard.
=================================================================
# As a fun experiment, change the Employee class so that it doesn't inherit
# from object (that makes it an old-style class). Observe the weird side
# effects, then make an angry post on your blog!
import sys
# Pretend this class was implemented in C++ and has a really annoying interface
# with a ton of getter and setter method.
class Employee(object):
def __init__(self, given_name, family_name, date_of_birth):
self.given_name = given_name
self.family_name = family_name
self.date_of_birth = date_of_birth
def GetGivenName(self): return self.given_name
def SetGivenName(self, value): self.given_name = value
def GetFamilyName(self): return self.family_name
def SetFamilyName(self, value): self.family_name = value
def GetDateOfBirth(self): return self.date_of_birth
def SetDateOfBirth(self, value): self.date_of_birth = value
# ad infinitum...
def properties(*args):
framedict = sys._getframe(1).f_locals
for propname, realname in args:
framedict[propname] = property(
fget=eval("lambda self: self.Get%s()" % realname),
fset=eval("lambda self, value: self.Set%s(value)" % realname)
)
# Let's make a nice wrapper for the Employee class that uses properties in
# place of the getter and setter methods. Also, let's shorten the names
# because we're lazy and don't like to type too much.
class PyEmployee(Employee):
properties(
('given', 'GivenName'),
('family', 'FamilyName'),
('birth', 'DateOfBirth'),
)
if __name__ == '__main__':
e = PyEmployee('Feihong', 'Hsu', '2007-11-15')
print e.given, e.GetGivenName(), e.given_name
e.given = 'Horatio' # change given name through the property
print e.given, e.GetGivenName(), e.given_name
---------------------------------
Get easy, one-click access to your favorites. Make Yahoo! your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/chicago/attachments/20071116/6326d67a/attachment.htm
More information about the Chicago
mailing list