Some problems with classes

Chris Rebert clp at rebertia.com
Mon Sep 1 03:50:24 CEST 2008


On Sun, Aug 31, 2008 at 6:39 PM, ssecorp <circularfunc at gmail.com> wrote:
> Why/how is it possible to add variables like this? I don't understand
> this mechanism:
> http://docs.python.org/tut/node11.html#SECTION0011330000000000000000

Under the covers, Python objects are implemented using dictionaries,
so adding an attribute just adds a new key-value pair to the object's
internal dictionary (which, incidentally, you can access as
someobj.__dict__).

>
> class Employee:
>    pass
>
> john = Employee() # Create an empty employee record
>
> # Fill the fields of the record
> john.name = 'John Doe'
> john.dept = 'computer lab'
> john.salary = 1000
>
> ---------------------------------------------------------------------------
>
> Also, I can't get multiple inheritance to work.
>
> Don't mind that the a vegan obviously don't inherit from an animal and
> a vegetable. I didn't come up with anything better, it is just to
> learn about inheritance.
>
>
> class Animal(object):
>    def __init__(self, name, weight):
>        self.name = name
>        self.weight = weight
>
>    def speak(self):
>        print "speak"
>
> class Vegetable(object):
>    def __init__(self, name, volume):
>        self.name = name
>        self.volume = volume
>
>    def split(self):
>        print "tjoff"
>
> class Vegan(Animal, Vegetable):
>    #pass
>    def __init__(self, name, attacks):
>        self.name = name
>        self.attacks = attacks
>
>>>>
>
> Traceback (most recent call last):
>  File "C:/Python25/Progs/XXXX/Movie.py", line 42, in <module>
>    class ActionComedy(Movie, ActionMovie):
> TypeError: Error when calling the metaclass bases
>    Cannot create a consistent method resolution
> order (MRO) for bases Movie, ActionMovie

The class names in error message here don't match the classes you
declared above. Give us the actual code you're using or at least a
stub version.

>>>>
>
>
> also, when inheriting, can I inherit __init__() somehow? If I want the
> same attributes but perhaps some additional methods for example.

Use super() to call your superclasses' __init__() methods. See
super()'s entry in http://docs.python.org/lib/built-in-funcs.html for
more info.

- Chris

>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list