Larry: Using "as", I cannot use both Circle and ColorCircle or more
like 3DCircle ... at the same time, only one of them.
But this is a easy solution in some cases.
On 31 mai, 00:25, Matimus <mccre...@gmail.comwrote:
Hi Martimus, your idea was a good one, I used it to meet my
_particular_ needs.
I was expecting something more complicate with metaclass, object
introspection ....
I used an interface (like in Java, a class with just method that must
work in //
with anoter class).
Finally the "replacement" of the base class in done with a simple :
class ColorCircle(ColorGraphInterface, Circle):
graph_base_class=Circle
Here is my full working test code
class Graph:
def plot(self):
print 'Graph.plot'
class Circle(Graph):
def draw(self):
print 'Circle.draw'
self.plot()
class Square(Graph):
def draw(self):
print 'Square.draw'
self.plot()
class ColorGraphInterface:
graph_base_class=None
def plot(self):
print 'ColorGraphInterface.plot'
self.graph_base_class.plot(self)
def draw(self):
print 'ColorGraphInterface.draw'
self.graph_base_class.draw(self)
class ColorCircle(ColorGraphInterface, Circle):
graph_base_class=Circle
class ColorCircle(ColorGraphInterface, Square):
graph_base_class=Square
cc=ColorCircle()
cc.draw()
This is a rather simplistic example, but you may be able to use a
mixin class to achieve what you need. The idea is that you write a
class that overrides only what is needed to add the new functionality.
For you it would be Color.
-
class Graph(object):
-
def _foo(self):
-
print "Graph._foo"
-
class Color(object):
-
def _foo(self):
-
print "Color._foo"
-
class Circle(Graph):
-
def bar(self):
-
self._foo()
-
class ColorCircle(Color,Circle): # the order of parent classes is
-
important
-
pass
-
if __name__ == "__main__":
-
c1 = Circle()
-
c2 = ColorCircle()
-
c1.bar() #prints: Graph._foo
-
c2.bar() #pritns: Color._foo
-
You might not have to do anything already. Try this and see if it
works:
-
ColorCircle(ColorGraph,Circle):
-
pass
-
Note that you will probably have to create an __init__ method, and
explicitly call the __init__ methods for the base classes. If the
__init__ for Circle ends up calling the __init__ method from Graph,
you may have issues. That is why the Color mixin that I created
inherited from object not Graph. It helps to avoid clashing __init__
methods.
Yes I know, super() do a great job for that :-)
>
Matt