3
class Email():
 def __init__(self, store_number):
 self.store_number = store_number
 def amethod(self):
 pass

What is the correct way to pass variables from a sub-class to a parent-class? should I do:

class MoreSpecificEmail():
 def __init__(self, store_number):
 Email.__init__(self, store_number=store_number)
 def another_method(self):
 pass

or:

class MoreSpecificEmail():
 def __init__(self, store_number):
 self.store_number = store_number
 Email.__init__(self, store_number=self.store_number)

I have just been using different abbreviations of store_number in each sub-class to help clarify what's going on in my head. I am sure that is the wrong way, though.

jww
104k107 gold badges454 silver badges975 bronze badges
asked Mar 18, 2015 at 15:56

1 Answer 1

4

What you currently have isn't inheritance; neither of your classes actually inherits from anything! Firstly, Email should be a "new-style class", inheriting from object:

class Email(object):
 # ^ note inheritance from object
 def __init__(self, store_number):
 self.store_number = store_number
 def amethod(self):
 pass

Then MoreSpecificEmail should inherit from Email - as it doesn't have any additional instantiation parameters, it can just use the inherited __init__ and doesn't need to define its own:

class MoreSpecificEmail(Email):
 # ^ note inheritance from Email
 # note no need to define __init__
 def another_method(self):
 pass

For an example where there are additional __init__ parameters, note that you should use super and rely on the superclass's __init__ to assign the parameters it takes - you only need to assign the attributes that don't get handled by the superclass:

class MoreSpecificEmail(Email):
 def __init__(self, store_number, something_else):
 super(MoreSpecificEmail, self).__init__(store_number)
 # ^ pass it straight on
 self.something_else = something_else
 def another_method(self):
 pass

For more information, see the Python class tutorial.

answered Mar 18, 2015 at 16:02
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I checked out that tutorial, but in it they dont use SuperClass(object):, they just use SuperClass: Is there a difference?
@MichaelBillingham there is in 2.x - the former creates a new-style class, the latter an old-style class. See e.g. python.org/doc/newstyle

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.