changing new style classes py2.2

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu May 30 04:29:35 EDT 2002


robert_kuzelj at yahoo.com (Robert Kuzelj) wrote in 
news:eaef2e43.0205291225.45a6b751 at posting.google.com:

>>>> #some examples
>>>class A(object):
>>>..def meth1(self): pass
>>>..def meth2(self): pass
> 
>>> A.__dict__["meth3"] = A.meth1
> this throws "TypeError: object does not support item assignment"
> this was perfectly legal in old style classes.
> 
> so i could at least workaround by writing the following code
>>>exec "A.%(name1)s = A.%(name2)s" % {"name1": "meth5", "name2": "meth1"}
><booh> not very clear or very pythonic.
> 
> the workaraound is simply ugly (and sure is slower).

But the usual way of doing this is neither slow nor ugly:

>>> setattr(A, "meth3", A.meth1)

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list