![]() |
|
[Tut] Overriding in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Overriding in Python (/thread-97998.html) |
[Tut] Overriding in Python - xSicKxBot - 10-29-2020 Overriding in Python In this article, we are going to explore the concept of overriding in Python. We are also going to explore what are magic methods and abstract classes. Introduction Overriding is an interesting concept in object-oriented programming. When the method definitions of a Base Class are changed in a Subclass (Derived) Class this is called a method override. You are keeping the same signature of the method but changing the definition or implementation of a method defined by one of the ancestors. There is no special syntax or additional keywords needed to do method overriding in Python. It is a very important object-oriented programming concept since it makes inheritance exploit its full power. In essence, you are not duplicating code, thus following the programming principle of DRY (do not repeat yourself), and you can enhance the method in the subclass. To understand the concept of overrides, you must know the basic concepts of object-oriented programming such as classes and inheritance. There are many resources on the internet about OOP. A really good resource is Finxter Academy’s object-oriented Python class: https://academy.finxter.com/university/object-oriented-python/ Need for Overrides In the following example, you see how inheritance works and the problem of not overriding a method in the subclass. The Parent class has a method Code: whoamiCode: “I am a parent”Code: ChildCode: whoamiCode: “I am a parent”Inheritance example with no method overriding: Code: class Parent(): def whoami(self): print("I am a parent") class Child(Parent): def play(self): print(" I am playing") child = Child()
child.whoami() # Output:
# I am a parentThe next example, shows how basic overriding works. In this example the Code: ChildCode: whoamiCode: ParentCode: whoamiCode: ChildCode: “I am a child”Basic Overriding example: Code: #Overriding
class Parent(): def whoami(self): print("I am a parent") class Child(Parent): def play(self): print(" I am playing") def whoami(self): print("I am a child") parent = Parent()
parent.whoami()
print()
child = Child()
child.whoami() # Output:
# I am a parent
# I am a childThe third example shows how you can extend a method in a Base Class by overriding the method in the Subclass. To do that we use the Code: super()The Code: EmployeeCode: __init__Code: showEmployeeThe Code: SalesmanCode: EmployeeCode: showEmployeeCode: EmployeeCode: showEmployeeCode: EmployeeCode: super()Code: SalesmanCode: super()Code: __init__Code: __init__Code: showEmployeeCode: showEmployeeCode: EmployeeA third class called Code: CEOCode: showEmployeeCode: CEOCode: class Employee(): def __init__(self, empno, ename, salary, deptno): self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee(self): print("Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format(self.Empno, self.Ename, self.Salary, self.Deptno)) class Salesman(Employee): def __init__(self, empno, ename, salary, deptno, comm): self.Commission = comm super().__init__(empno, ename, salary, deptno) def showEmployee(self): print("Salesman Profile") super().showEmployee() print("Commision : ", self.Commission) class CEO(Employee): def __init__(self, empno, ename, salary, deptno, stock): self.Stock = stock super().__init__(empno, ename, salary, deptno) def showEmployee(self): print("CEO Profile") super().showEmployee() print("Stock Options : ", self.Stock) salesman = Salesman(200, "John Doe", 67000, "Sales", 100)
salesman.showEmployee()
print("")
ceo = CEO(40, "Jennifer Smith", 300000, "Director", 1000000)
ceo.showEmployee()Output: Code: Salesman Profile
Employee # : 200
Employee Name : John Doe
Salary : 67000
Department : Sales
Commision : 100 CEO Profile
Employee # : 40
Employee Name : Jennifer Smith
Salary : 300000
Department : Director
Stock Options : 1000000Understanding multiple inheritance has its own challenges. One of them is the use of Code: super()In the example below, I wanted to show a way to override a method from a subclass with multiple inheritance. The example consists of three classes: Code: AccountCode: CustomerCode: Orders
Here’s an example: Code: class Account(): def __init__(self, name, number): self.Name = name self.Number = number def display(self): print("Account # : {}\nAccount Name : {}".format(self.Number, self.Name)) class Customer(): def __init__(self, name, number): self.Name = name self.Number = number def display(self): print("Customer # : {}\nCustomer Name : {}".format(self.Number, self.Name)) class Orders(Account, Customer): def __init__(self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty): self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account(acctname, acctnumber) self.cust = Customer(custname, custnumber) def display(self): print("Order Information") self.acct.display() self.cust.display() print("Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format(self.OrdNumber, self.OrdName, self.Product, self.Qty)) acct = Account("AB Enterprise", 12345)
acct.display()
print("")
cust = Customer("John Smith", 45678)
cust.display()
print("")
order = Orders(12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, )
order.display()Output: Code: Account # : 12345
Account Name : AB Enterprise Customer # : 45678
Customer Name : John Smith Order Information
Account # : 12345
Account Name : AB Enterprise
Customer # : 45678
Customer Name : John Smith
Order # : 1
Order Name : Order 1
Product : Widget
Quantiy : 51 – Class Methods Class methods are special in the sense that they can be called on a class by itself or by instances of a class. They bind to a class so this means that the first argument passed to the method is a class rather than an instance. Class methods are written similarly to regular instance methods. One difference is the use of the decorator Code: @classmethodCode: clsCode: class Account(): @classmethod def getClassVersion(cls): print("Account class version is 1.0”)For more information about class methods check thiswebsite. Here is an example of the problem you will encounter when overriding a class method: Code: class ParentClass: @classmethod def display(cls, arg): print("ParentClass") class SubClass(ParentClass): @classmethod def display(cls, arg): ret = ParentClass.create(cls, arg) print("Subclass") return ret SubClass.display("test")Output: Code: create() takes 2 positional arguments but 3 were givenIn the Code: SubclassCode: ParentClassThe solution is to use Code: super()Code: class ParentClass: @classmethod def display(cls, arg): print("ParentClass") class SubClass(ParentClass): @classmethod def display(cls, arg): ret = super(SubClass, cls).create(arg) print("Subclass") return ret SubClass.display("test")Output: Code: ParentClass
Subclass2 – Magic Methods What are magic methods? Magic methods are a set of methods that Python automatically associates with every class definition. Your classes can override these magic methods to implement different behaviors and make them act just like Python’s built-in classes. Below you will see examples of two of the most common ones: Code: __str__Code: __repl__The Code: __str__Code: strCode: class DemoMagic(): def display(self): print("Demo Magic class") varDemo = DemoMagic()
varDemo.display()
str(varDemo)Output: Code: Demo Magic class '<__main__.DemoMagic object at 0x000002A7A7F64408>' class DemoMagic():
def display(self): print("Demo Magic class") def __str__(self): return "Override of str function" varDemo = DemoMagic()
varDemo.display()
str(varDemo)Output: Code: Demo Magic class 'Override of str function'The Code: __repr__Code: reprCode: class Person(object): def __init__(self, firstname, lastname): self.first = firstname self.last = lastname def __repr__(self): return "%s %s" % (self.first, self.last) Tom = Person("Tom", "Sawyer")
repr(Tom)Output Code: 'Tom Sawyer'Here is a list of magic methods. You can learn more about them here (https://www.tutorialsteacher.com/python/magic-methods-in-python) and think how to override them to fit your needs: Code: '__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__'An abstract class is a blueprint that subclasses must follow. It can be viewed as a contract between the abstract class and the subclass. The abstract class tells you what to do by providing an empty abstract method and the subclass must implement it. By default, you must override the abstract methods defined by the abstract class. In other terms, we are providing a common interface for different implementations of a class. This is very useful for large projects where certain functionality must be implemented. Here is an example of an abstract class and the overrriden methods in the subclasses. Code: from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def whoami(self): pass class Dog(Animal): def move(self): print("I am a dog") class Cat(Animal): def move(self): print("I am a cat")Overriding is a basic concept used in many places in object-oriented programming. You must understand it to be able to implement better classes and modify their behavior. This article shows you some examples where you can use overrides in Python. Other concepts mentioned that are worth learning more about are: magic method and abstract classes. The post Overriding in Python first appeared on Finxter. |