Python Classroom Series – 21/Jun/2021

Class Methods

  • Class methods effect the Class i.e. they operate on Class attributes.
class Mobile:
    # class attribute
    count = 0

    def __init__(self, model, manufacturer):
        # instance attribute
        self.model = model
        self.manufacturer = manufacturer
        Mobile.count += 1

    def dail(self, number):
        # instance
        print(f"dailing from {self.model} to {number}")

    @classmethod
    def count_info(cls):
        print(cls.count)

iphone = Mobile(model='12 PRO', manufacturer='apple')
iphone.dail('9999999999')
Mobile.count_info()

oneplus = Mobile(model='One plus 9', manufacturer='one plus')
oneplus.dail('888888888')
Mobile.count_info()

### Output

dailing from 12 PRO to 9999999999
1
dailing from One plus 9 to 888888888
2

Static Method

  • Static Methods are generally used to write utility functions.
  • Static methods affect neither class nor its objects. Its just in there for convenience
class Mobile:
    # class attribute
    count = 0

    def __init__(self, model, manufacturer):
        # instance attribute
        self.model = model
        self.manufacturer = manufacturer
        Mobile.count += 1

    def dail(self, number):
        # instance
        print(f"dailing from {self.model} to {number}")

    @classmethod
    def count_info(cls):
        print(cls.count)

    @staticmethod
    def copyright():
        print(f"Copyright @2021. Any illegal reproduction of this content will result in immediate legal action ")

iphone = Mobile(model='12 PRO', manufacturer='apple')
iphone.dail('9999999999')
Mobile.count_info()

oneplus = Mobile(model='One plus 9', manufacturer='one plus')
oneplus.dail('888888888')
Mobile.count_info()
Mobile.copyright()

Magic Methods

  • In python we have lot of magical methods

  • Refer Here for the official documentation

  • Magical methods for comparison

Method Description
__eq__(self, other) self == other
__ne__(self, other) self != other
__lt__(self, other) self < other
__gt__(self, other) self > other
__le__(self, other) self <= other
__ge__(self, other) self >= other
  • Magical Methods for math
Method Description
__add__(self, other) self + other
__sub__(self, other) self – other
__mul__(self, other) self * other
__floordiv__(self, other) self // other
__truediv__(self, other) self/other
__mod__(self, other) self % other
__pow__(self, other) self ** other
  • Miscellaneous Magic methods
Method Description
str(self) str(self)
repr(self) repr(self)
len(self) len(self)

Inheritance

  • Inherit from Parent Class

class Mobile:
    pass

class SmartMobile(Mobile):
    pass

  • We can check the relationship using issubclass
>>> issubclass(SmartMobile, Mobile)
True
  • Lets add behaviours to the parent class
  • Override the Methods and Magical Methods
  • Refer Here for the examples

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin