Re: How to subclass a family

Discussion in 'Python' started by Arnaud Delobelle, Apr 8, 2013.

  1. On 8 April 2013 10:44, Antoon Pardon <> wrote:
    > Here is the idea. I have a number of classes with the same interface.
    > Something like the following:
    >
    > class Foo1:
    > def bar(self, ...):
    > work
    > def boo(self, ...):
    > do something
    > self.bar(...)
    >
    > What I want is the equivallent of:
    >
    > class Far1(Foo1):
    > def boo(self, ...)
    > do something different
    > if whatever:
    > self.bar(...)
    > else:
    > Foo1.boo(self, ...)
    >
    > Now of course I could subclass every class from the original family
    > from Foo1 to Foon but that would mean a lot of duplicated code. Is
    > there a way to reduce the use of duplicated code in such circumstances?
    >


    (Python 3)
    ------------------------------
    class Foo1:
    def bar(self):
    print('Foo1.bar')
    def boo(self, whatever):
    print('Foo1.boo', whatever)
    self.bar()

    # class Foo2: ...(I'll let you define this one)

    class DifferentBoo:
    def boo(self, whatever):
    print('DifferentBoo.boo', whatever)
    if whatever:
    self.bar()
    else:
    super().boo(whatever)

    class Far1(DifferentBoo, Foo1): pass
    # class Far2(DifferentBoo, Foo2): pass

    ------------------------------
    >>> foo = Foo1()
    >>> foo.bar()

    Foo1.bar
    >>> foo.boo(1)

    Foo1.boo 1
    Foo1.bar
    >>> far = Far1()
    >>> far.bar()

    Foo1.bar
    >>> far.boo(0)

    DifferentBoo.boo 0
    Foo1.boo 0
    Foo1.bar
    >>> far.boo(1)

    DifferentBoo.boo 1
    Foo1.bar

    HTH,

    --
    Arnaud
    Arnaud Delobelle, Apr 8, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jstorta
    Replies:
    3
    Views:
    441
    jstorta
    Feb 20, 2006
  2. S.Volkov
    Replies:
    2
    Views:
    215
    S.Volkov
    Mar 12, 2006
  3. Trans
    Replies:
    8
    Views:
    320
    Robert Klemme
    Oct 23, 2008
  4. Antoon Pardon

    How to subclass a family

    Antoon Pardon, Apr 8, 2013, in forum: Python
    Replies:
    1
    Views:
    113
    Steven D'Aprano
    Apr 9, 2013
  5. Devin Jeanpierre

    Re: How to subclass a family

    Devin Jeanpierre, Apr 9, 2013, in forum: Python
    Replies:
    0
    Views:
    302
    Devin Jeanpierre
    Apr 9, 2013
Loading...

Share This Page