Note that there are some explanatory texts on larger screens.

plurals
  1. POVirtual classes: doing it right?
    primarykey
    data
    text
    <p>I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the parameters it is given and hand that back the calling function. For now I have a summary way of rerouting calls to the virtual class down to the underlying class.</p> <p>The idea is the following:</p> <pre><code>class Shape: def __init__(self, description): if description == "It's flat": self.underlying_class = Line(description) elif description == "It's spiky": self.underlying_class = Triangle(description) elif description == "It's big": self.underlying_class = Rectangle(description) def number_of_edges(self, parameters): return self.underlying_class(parameters) class Line: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 1 class Triangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 3 class Rectangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 4 shape_dont_know_what_it_is = Shape("It's big") shape_dont_know_what_it_is.number_of_edges(parameters) </code></pre> <p>My rerouting is far from optimal, as only calls to the number_of_edges() function get passed on. Adding something like this to Shape doesn't seam to do the trick either:</p> <pre><code>def __getattr__(self, *args): return underlying_class.__getattr__(*args) </code></pre> <p>What I am doing wrong ? Is the whole idea badly implemented ? Any help greatly appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload