Python Classroom Series – 05/Sept/2021

Magic Methods

  • Magic methods for comparision
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
  • Example implementation of eq
class Car:
    def __init__(self, name, registration_number) -> None:
        self.name = name
        self.registration_number = registration_number

    def __eq__(self, other: "Car") -> bool:
        return self.name == other.name and self.registration_number == other.registration_number


car1 = Car('City', '1234')
car2 = Car('City', '1234')
car3 = Car('Swift', '2345')

print(car1 == car2)
print(car1 == car3)
        
  • Other magic methods
    • __str__(self): str(self)
    • __repr__(self): repr(self)
    • __len__(self): len(self)
  • Refer Here for the special methods

Named Tuple

  • A named tuple is a subclass of tuples with which you can access values by name (with .name) as well as position(with [offset]) Preview
  • Named tuples are immutable but we can replace one or more fields and return another named tuple Preview

Dataclasses

  • We like to create objects mainly to store data (as object attributes), not so much behavior
class Mobile:
    def __init__(self, model, os):
        self.model = model
        self.os = os
  • We can do the same thing with data classes
from dataclasses import dataclass

@dataclass
class Mobile:
    name: str
    model: str
    price: float
    os: str
    

if __name__ == '__main__':
    iphone = Mobile('iphone','iphone 12 promax',120000, 'ios' )
    print(iphone.name)
    oneplus = Mobile('oneplus', '9T', 80000, 'oxygen')
    print(oneplus.model)

Exercise

  • We want to build a library management system which allows
    • To register users
    • To add employees
    • To borrow and return books
  • Initially we would want to build a command line application and then we would build a web site (when we learn django)
  • Kindly come up with the class diagram for this project
  • Suggest command line or help for library management as what is shown for ping Preview
  • Have the first version ready by 07 Sep 2021

Leave a Comment

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

About learningthoughtsadmin