Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Advanced Object-Oriented Programming in Python

Tech Dec 5 5

Type Checking with isinstance and issubclass

isinstance(obj, cls) verifies if obj is an instance of class cls:

class Animal:
    pass

dog = Animal()
print(isinstance(dog, Animal))  # True

issubclass(sub, super) checks if sub is a subclass of super:

class Pet(Animal):
    pass

print(issubclass(Pet, Animal))  # True

Reflection in Python

Reflection allows programs to inspect and modify their own structure at runtime. Python provides four key functions:

class User:
    def __init__(self, username):
        self.username = username

user = User('admin')

# Check attribute existence
print(hasattr(user, 'username'))  # True

# Get attribute value
print(getattr(user, 'username', 'guest'))  # 'admin'

# Set attribute
setattr(user, 'role', 'administrator')

# Delete attribute
delattr(user, 'role')

String Representation Methods

Customize object string display with __str__ and __repr__:

class Coordinate:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __str__(self):
        return f"Point({self.x}, {self.y})"
        
    def __repr__(self):
        return f"Coordinate({self.x}, {self.y})"

coord = Coordinate(3, 4)
print(str(coord))    # Point(3, 4)
print(repr(coord))   # Coordinate(3, 4)

Special Methods

Object Initialization and Cleanup

class Resource:
    def __init__(self, name):
        self.name = name
        print(f"Resource {name} allocated")
        
    def __del__(self):
        print(f"Resource {self.name} released")

res = Resource('DB')
del res

Dictionary-style Access

class Config:
    def __init__(self):
        self.settings = {}
        
    def __getitem__(self, key):
        return self.settings[key]
        
    def __setitem__(self, key, value):
        self.settings[key] = value
        
    def __delitem__(self, key):
        del self.settings[key]

config = Config()
config['timeout'] = 30
print(config['timeout'])

Object Callability

class Multiplier:
    def __call__(self, x, y):
        return x * y

multiply = Multiplier()
print(multiply(5, 6))  # 30

Property Decorators

class Circle:
    def __init__(self, radius):
        self.radius = radius
        
    @property
    def diameter(self):
        return 2 * self.radius
        
    @property
    def area(self):
        return 3.14 * self.radius ** 2

circle = Circle(5)
print(circle.diameter)  # 10
print(circle.area)      # 78.5

Class Methods

class Logger:
    log_level = 'INFO'
    
    @classmethod
    def set_level(cls, level):
        cls.log_level = level

Logger.set_level('DEBUG')
print(Logger.log_level)  # DEBUG

Static Methods

class MathUtils:
    @staticmethod
    def add(x, y):
        return x + y

print(MathUtils.add(2, 3))  # 5

Multiple Inheritance

class Flyer:
    def fly(self):
        print("Flying")

class Swimmer:
    def swim(self):
        print("Swimming")

class Duck(Flyer, Swimmer):
    pass

duck = Duck()
duck.fly()
duck.swim()
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.