data strucutures in python
Jeff Petkau
jpet at eskimo.com
Thu Sep 21 01:42:04 EDT 2000
Kragen Sitaker <kragen at dnaco.net> wrote in message
news:jlWx5.448$mc3.45617 at news-east.usenetserver.com...
> I was chatting with a coworker about this today. He mentioned that C#
> has a neat way of declaring active properties --- you say something
> like:
>
> class foo {
> property lambda {
> int get() { code here }
> void set() { code here }
> };
> };
>
> and then the code in the get and set "methods" will be invoked to
> implement reading or writing the property "lambda" of any object of the
> class "foo".
How about this:
# evil_things.py ---------------
def magic_getattr(self,name):
return getattr(self,'get'+name)()
def magic_setattr(self,name,value):
return apply(getattr(self,'set'+name),(value,))
#------------------------------
# test.py -------------------
# See how those evil things work
import evil_things
class C:
def getX(self):
return 3
def setX(self,value):
print "ha! still 3"
__getattr__ = evil_things.magic_getattr
__setattr__ = evil_things.magic_setattr
# now C has properties!
c = C()
c.X = 20
--> ha! still 3
print c.X
--> 3
ps. Don't try this at home.
--Jeff (jpet at eskimo.com)
More information about the Python-list
mailing list