PythonObjectOriented: Difference between revisions

From Traxel Wiki
Jump to navigation Jump to search
Line 39: Line 39:
data_manager = DataManager('data.json')
data_manager = DataManager('data.json')
print(data_manager.get_data_by_key('some_key'))
print(data_manager.get_data_by_key('some_key'))
</syntaxhighlight>
= Abstract Class =
<syntaxhighlight lang="python" line>
from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
    @abstractmethod
    def perimeter(self):
        pass
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
    def perimeter(self):
        return 2 * (self.width + self.height)
# r = Shape()  # TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeter
rect = Rectangle(10, 20)
print(rect.area())
print(rect.perimeter())
</syntaxhighlight>
</syntaxhighlight>

Revision as of 04:39, 3 November 2023

Singleton

import json
from threading import Lock

class SingletonMeta(type):
    _instances = {}
    _lock: Lock = Lock()
    
    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
            return cls._instances[cls]

class DataManager(metaclass=SingletonMeta):
    def __init__(self, filename):
        self.filename = filename
        self.data = None
        self.index = None
        self.load_data()

    def load_data(self):
        with open(self.filename, 'r') as file:
            self.data = json.load(file)
        self.index_data()

    def index_data(self):
        # Implement your indexing logic here.
        # For example, if your data is a list of dicts:
        self.index = {d['key']: d for d in self.data}

    def get_data_by_key(self, key):
        return self.index.get(key)

# Usage:
data_manager = DataManager('data.json')
print(data_manager.get_data_by_key('some_key'))

Abstract Class

from abc import ABC, abstractmethod

class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

# r = Shape()  # TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeter
rect = Rectangle(10, 20)
print(rect.area())
print(rect.perimeter())