Python: How to create a subclass from a superclass?

In Python, how do you create a subclass from a superclass?

+48
python class
Oct 22 '09 at 14:26
source share
11 answers

Using "super" (see Python Built-in , super) may be a slightly better method to call the parent for initialization:

# Initialize using Parent # class MySubClass(MySuperClass): def __init__(self): MySuperClass.__init__(self) # Better initialize using Parent (less redundant). # class MySubClassBetter(MySuperClass): def __init__(self): super(MySubClassBetter, self).__init__() 
+56
Oct 22 '09 at 17:54
source share

Heroic example:

 class SuperHero(object): #superclass, inherits from default object def getName(self): raise NotImplementedError #you want to override this on the child classes class SuperMan(SuperHero): #subclass, inherits from SuperHero def getName(self): return "Clark Kent" class SuperManII(SuperHero): #another subclass def getName(self): return "Clark Kent, Jr." if __name__ == "__main__": sm = SuperMan() print sm.getName() sm2 = SuperManII() print sm2.getName() 
+45
Oct 22 '09 at 14:39
source share
 class MySubClass(MySuperClass): def __init__(self): MySuperClass.__init__(self) # <the rest of your custom initialization code goes here> 

the inheritance section of the python documentation explains this in more detail

+30
Oct 22 '09 at 14:28
source share
 class Class1(object): pass class Class2(Class1): pass 

Class2 is a subclass of Class1

+7
Oct 22 '09 at 14:28
source share

You're using:

 class DerivedClassName(BaseClassName): 

See Python Docs, section 9.5 for more information .

+3
Oct 22 '09 at 14:28
source share

There is another way to dynamically subclass in python using the type() function:

 SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__() 

You usually use this method when working with metaclasses. When you want to do a few lower levels of automation, this changes the way you create a python class. Most likely, you will never need to do it this way, but when you do this, you will already know what you are doing.

+2
Sep 17 '14 at 19:48
source share
 class Subclass (SuperClass): # Subclass stuff here 
+1
Oct 22 '09 at 14:28
source share
 class Mammal(object): #mammal stuff class Dog(Mammal): #doggie stuff 
+1
Oct 22 '09 at 14:28
source share

A subclass in Python runs as follows:

 class WindowElement: def print(self): pass class Button(WindowElement): def print(self): pass 

Here is a Python tutorial that also contains classes and subclasses.

0
Oct 22 '09 at 14:31
source share

In the above answers, super initialized with no arguments (keyword). Often, however, you would like to do this, as well as pass some of your own “own” arguments. Here is an example illustrating this use case:

 class SortedList(list): def __init__(self, *args, reverse=False, **kwargs): super().__init__(*args, **kwargs) # Initialize the super class self.reverse = reverse self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments 

This is a subclass of list , which, upon initialization, immediately sorts itself in the direction indicated by the argument to the reverse keyword, as the following tests show:

 import pytest def test_1(): assert SortedList([5, 2, 3]) == [2, 3, 5] def test_2(): SortedList([5, 2, 3], reverse=True) == [5, 3, 2] def test_3(): with pytest.raises(TypeError): sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument if __name__ == "__main__": pytest.main([__file__]) 

Thanks to the transfer from *args to super list can be initialized and filled with elements, and not just empty. (Note that reverse is a keyword-only argument according to PEP 3102 ).

0
Nov 21 '17 at 1:46 on
source share
 class BankAccount: def __init__(self, balance=0): self.balance = int(balance) def checkBalance(self): ## Checking opening balance.... return self.balance def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly. self.deposit_amount = deposit_amount self.balance += deposit_amount return self.balance def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"` return 'invalid transaction' else: self.balance -= withdraw_amount return self.balance class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class def __init__(self,balance=0, minimum_balance=500): BankAccount.__init__(self, balance=0) self.minimum_balance = minimum_balance self.balance = balance - minimum_balance #print "Subclass MinimumBalanceAccount of the BankAccount class created!" def MinimumBalance(self): return self.minimum_balance c = BankAccount() print(c.deposit(50)) print(c.withdraw(10)) b = MinimumBalanceAccount(100, 50) print(b.deposit(50)) print(b.withdraw(10)) print(b.MinimumBalance()) 
-one
Jul 05 '16 at 22:54
source share



All Articles