2

So for some reason, I have to create multiple classes. Just like this code

class Myclass1:
    do_x

class Myclass2:
    do_x

class Myclass3:
    do_x

Currently, I can do that by copying do_x over and over. However it seems not effective. Any better idea?

2
  • 3
    Have you heard of inheritance? You can make an abstract base class with whatever common methods and inherit from that docs.python.org/2/library/abc.html Commented Aug 29, 2015 at 9:29
  • What you are looking for is inheritance Commented Aug 29, 2015 at 9:30

2 Answers 2

1

What you are trying to do is inheritance.

class Myclass:
    def do_x(self):
        pass

class My_child(Myclass):
    def do_x(self):
        print("I am the chile class")

class My_2nd_child(Myclass):
    def do_x(self):
        print("I am the 2nd child")

The base class in this case has a stub for method do_x.

The child classes override that method to implement their own behaviors.

Inheritance is mostly useful for code reuse (DRY principle)

Sign up to request clarification or add additional context in comments.

Comments

1

Continuing with the answer given by @Reblochon Masque... There is another advantages here using super method is to execute child class method along with parent method.

  class Myclass(object):
    def do_x(self):
       print 'In parent Class'

  class Myfirstchild(Myclass):
    def do_x(self):
      print 'In child class';
      super(Myfirstchild, self).do_x()

Here the output/result would be

   In child class
   In parent Class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.