Could anyone explain __class__?
Alex
new_name at mit.edu
Sat May 19 11:34:35 EDT 2001
> I'm having trouble understanding the function of the built-in class
> method __class__. The documentation is terse, to say the least.
>
> From code examples (UserList.py, forex.), it appears that
> self.__class__() returns a new instance of the class of the instance
> in which it is called.
The idea with UserList is that it's to be inherited from. See
http://www.python.org/doc/current/tut/node11.html#SECTION0011500000000000000000
for a brief explanation. UserList instantiates return values using the
class referred to by the self.__class__ attribute because in most cases
it's expected that adding two instances of a class will return another
instance of that class, and self.__class__ is just the class of the
instance calling the current method. Here's a simple example:
from UserList import UserList
class MyList(UserList):
'''A subclass of UserList with a frivolous attribute.'''
def __init__(self, initlist=None):
UserList.__init__(self, initlist)
self.my_frivolous_attribute = None
l = MyList([1])
m = MyList([2])
new_mylist = l+m
assert (new_mylist.__class__ == MyList) and \
hasattr(new_mylist, 'my_frivolous_attribute')
HTH
Alex.
More information about the Python-list
mailing list