changing new style classes py2.2

David Abrahams david.abrahams at rcn.com
Wed May 29 17:28:44 EDT 2002


"Robert Kuzelj" <robert_kuzelj at yahoo.com> wrote in message
news:eaef2e43.0205291225.45a6b751 at posting.google.com...
> hi,
>
> i am having some problems using new style classes.
> i want to build something like an class-enhancer
> so i need write-access to the class.__dict__.
> but this seems to be forbidden now as opposed
> to oldsytle classes.
>
> >>> #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.
>
> on the other hand this is still legal (that means
> it still works without error).
> >>A.meth3 = A.meth1
>
> 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.
>
> besides the fact, that this behaviour seems to be inconsistent
> with the old-style it is inconsistent with it self. either one
> can change a class (then it should be possible by writing to
> the __dict__) or one can not.
>
> the workaraound is simply ugly (and sure is slower).

This doesn't look so terrible to me:

Python 2.2.1 (#34, Apr 12 2002, 16:47:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...     def meth1(self):pass
...     def meth2(self):pass
...
>>> setattr(A,"meth3",A.meth1)
>>> a = A()
>>> a.meth3
<bound method A.meth1 of <__main__.A object at 0x00876688>>
>>> a.meth3()
>>>





More information about the Python-list mailing list