Could anyone explain __class__?
> 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
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
'''A subclass of UserList with a frivolous attribute.'''
def __init__(self, initlist=None):
self.my_frivolous_attribute = None
l = MyList()
m = MyList()
new_mylist = l+m
assert (new_mylist.__class__ == MyList) and \