Instances behaviour
Inyeol Lee
inyeol.lee at siliconimage.com
Thu Dec 1 19:55:58 EST 2005
On Thu, Dec 01, 2005 at 03:51:05PM -0800, Mr.Rech wrote:
[...]
> Suppose I have a bunch of classes that represent slightly (but
> conceptually) different object. The instances of each class must behave
> in very similar manner, so that I've created a common class ancestor
> (let say A) that define a lot of special method (such as __getattr__,
> __setattr__, __len__ and so on), and then I've created all my "real"
> classes inheriting from it:
>
> >>>class A(object):
> .... # here define all special and some common methods
>
> >>> class B(A):
> .... # this is the first "real" class
>
> >>> class C(A):
> .... # and this is the second
>
> and so on. The problem I'm worried about is that an unaware user may
> create an instance of "A" supposing that it has any real use, while it
> is only a sort of prototype. However, I can't see (from my limited
> point of view) any other way to rearrange things and still get a
> similar behaviour.
>>> class A(object):
>>> ... def __init__(self, foo):
>>> ... if self.__class__ is A:
>>> ... raise TypeError("A is base class.")
>>> ... self.foo = foo
>>> ...
>>> class B(A):
... pass
...
>>> class C(A):
... def __init__(self, foo, bar):
... A.__init__(self, foo)
... self.bar = bar
...
>>> a = A(1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __init__
TypeError: A is base class.
>>> b = B(1)
>>> b.foo
1
>>> c = C(1, 2)
>>> c.foo, c.bar
(1, 2)
>>>
HTH
--Inyeol Lee
More information about the Python-list
mailing list