#๐Ÿ”’ HOW TO DO ABSTRACTION WITHOUT ABC

23 messages ยท Page 1 of 1 (latest)

forest owl
#

AM I CORRECT IN THIS APPROACH? WHAT ELSE NEED TO DO?

class CAR:
def init(self, car_model):
self.car_model = car_model

MADE ABSTRACT FUNCTION (METHOD)

def Car_Model(self):
    pass

MADE METHODS LIKE CONCRETE FUNCTIONS IN ABC

def KeyOn(self):
    return f"{self.car_model} : STARTS..."

def Car_Acclerate(self):
    return f"{self.car_model} : ACCELERATE"

def Car_Break(self):
    return f"{self.car_model} : APPLIES BRAKE.."

def keyOFF(self):
    return f"{self.car_model} : STOPS..."

class Toyota(CAR):
def Car_Model(self):
return f"Car Model : {self.car_model}"

def KeyOn(self):
    return super().KeyOn()

def Car_Acclerate(self):
    return super().Car_Acclerate()

def Car_Break(self):
    return super().Car_Break()

def keyOFF(self):
    return super().keyOFF()

fortuner = Toyota("Fortuner")
print(fortuner.Car_Model())
print(fortuner.KeyOn())
print(fortuner.Car_Acclerate())
print(fortuner.Car_Break())
print(fortuner.keyOFF())

hard juncoBOT
#

@forest owl

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

heavy dome
#

What's the reason behind this?

tiny tulip
#

Do you know how to use abc?

forest owl
heavy dome
#

making ABSTRACTION without ABC

forest owl
forest owl
tiny tulip
heavy dome
#

ok..

  1. NotImplementedError
  2. Method Stubs with Documentation
  3. Custom Metaclasses
  4. init_subclass Hook
    finaly... Duck Typing
#

most people will go for Duck Typing

#

you need some examples ? @forest owl

forest owl
tiny tulip
#

decorators
decorator factories
overloading functions and methods

heavy dome
#

NotImplementedError

class Animal:
    def speak(self):
        raise NotImplementedError("Subclass must implement speak()")

class Dog(Animal):
    def speak(self):
        return "Woof!"

# Raises error if not implemented
# cat = Animal()  # Error!
#

Method Stubs + Docs

class Database:
    def connect(self):
        """Must be implemented by subclasses"""
        pass

class MySQL(Database):
    def connect(self):
        return "Connected!"

# Fails silently if not overridden
# db = Database()  # No error (but useless)
#

Custom Metaclass

class AbstractMeta(type):
    def __new__(cls, name, bases, attrs):
        if "save" not in attrs:
            raise TypeError(f"{name} must implement 'save()'")
        return super().__new__(cls, name, bases, attrs)

class Model(metaclass=AbstractMeta):
    pass

# Raises TypeError if 'save' is missing
# class User(Model): pass  # Error!
class User(Model):
    def save(self): pass  # OK
#

Decorator (@abstractmethod-like)

def abstractmethod(func):
    func.__is_abstract__ = True
    return func

class Shape:
    @abstractmethod
    def area(self): pass

    def __init_subclass__(cls):
        for name, method in vars(cls).items():
            if getattr(method, "__is_abstract__", False):
                raise TypeError(f"Can't instantiate {cls.__name__} without {name}()")

# Raises TypeError if 'area' is missing
# class Circle(Shape): pass  # Error!
#

__init_subclass__ Hook

class Plugin:
    required = ["run"]

    def __init_subclass__(cls):
        missing = [method for method in cls.required if method not in vars(cls)]
        if missing:
            raise TypeError(f"Missing required methods: {missing}")

# Raises TypeError if 'run' is missing
# class MyPlugin(Plugin): pass  # Error!
class MyPlugin(Plugin):
    def run(self): pass  # OK
#

Duck Typing (No Enforcement)

# No parent class! Just assume objects have the method.
def log_to_db(storage):
    storage.save()  # Crashes at runtime if .save() is missing

class DiskStorage:
    def save(self): print("Saved!")

log_to_db(DiskStorage())  # Works
# log_to_db(object())  # Fails at runtime```
#

these are my old notes.. hope it help u out @forest owl

hard juncoBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.