Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • Tags
  • Connexion

Classes and Objects/shaare/Qakaww

  • python
  • python

Classes and Objects

  • Beyond Built-ins: Python lets you define your own data types using class.
  • Class: A blueprint or template for creating objects. Defines attributes (data) and methods (behavior). Convention: PascalCase names (MyClass).
  • Object (Instance): A specific item created from a class blueprint. Each object has its own set of attribute values but shares the methods defined by the class. obj1 = MyClass(), obj2 = MyClass(). obj1 and obj2 are distinct objects.

Defining a Class & __init__ (The Constructor)

  • __init__(self, ...): Special method for initialization. self is always the first parameter and represents the instance itself. Other parameters receive arguments passed during object creation.
  • Instance Attributes (self.x = ...): Data attached to this specific object. Created inside methods (usually __init__) using self.attribute_name = value.
class ServiceMonitor:
    """Provides service checks for a single service"""
    def __init__(self, service_name, port):
        """Initializes the monitor for a specific service.

        Args:
            service_name (str): the name of the service.
            port (int): the port to use for checks.
        """
        print(f"Initializing monitor for service {service_name} on port {port}.")
        self.service = service_name
        self.port = port
        self.is_alive = False

Creating Instances (Objects)

  • Mechanism: Call the class name as if it were a function, passing any arguments required by __init__ (after self).
  • Python automatically creates the object and passes it as self to __init__.
nginx_monitor = ServiceMonitor("nginx", 80)
print(isinstance(nginx_monitor, ServiceMonitor))

redis_monitor = ServiceMonitor(service_name="redis", port=6379)
print(isinstance(redis_monitor, ServiceMonitor))

print(nginx_monitor.service)
print(redis_monitor.service)

Instance Methods: Object Behavior

  • Definition: Functions defined inside a class definition.
  • First Parameter: Always self (by strong convention), allowing the method to access and modify the instance's attributes (self.attribute_name).
  • Calling: Use dot notation on an instance: instance.method_name(arguments). Python automatically passes the instance (instance) as the self argument.
class ServiceMonitor:
    """Provides service checks for a single service"""
    def __init__(self, service_name, port):
        """Initializes the monitor for a specific service.

        Args:
            service_name (str): the name of the service.
            port (int): the port to use for checks.
        """
        print(f"Initializing monitor for service {service_name} on port {port}.")
        self.service = service_name
        self.port = port
        self.is_alive = False

    def check(self):
        """Simulates checking the service status"""
        print(f"METHOD: Checking {self.service} on port {self.port}...")
        self.is_alive = True
        print(f"METHOD: Status for service {self.service}: {"Alive" if self.is_alive else "Down"}")
        return self.is_alive

nginx_monitor = ServiceMonitor("nginx", 80)
status = nginx_monitor.check()
print(f"Received status: {status}")

Basic Inheritance: Reusing and Extending

  • Concept: Create a new class (Child/Subclass) that inherits properties (attributes and methods) from an existing class (Parent/Superclass). Promotes code reuse (DRY).
  • Syntax: class ChildClassName(ParentClassName):
  • Inherited Members: The Child automatically gets all methods and attributes defined in the Parent.
  • Specializing: The Child can:
    • Add new attributes and methods.
    • Override parent methods by defining a method with the same name.
  • super(): Inside the Child's methods, use super().method_name(...) to explicitly call the Parent's version of a method (very common in __init__).
class HttpServiceMonitor(ServiceMonitor):
    """Extends ServiceMonitor to add an HTTP endpoint check."""
    def __init__(self, service_name, port, url):
        super().__init__(service_name, port)
        self.url = url

    def ping(self):
        """Ping url provided when creating instance."""
        print(f"METHOD: Pinging url {self.url}")

    def check(self):
        alive = super().check()
        print(f"METHOD: Performing HTTP check on {self.url}")

http_monitor = HttpServiceMonitor("web", 8080, "http://localhost")
nginx_monitor = ServiceMonitor("nginx", 80)

http_monitor.ping()
http_monitor.check()
# nginx_monitor.ping() # Uncommenting will raise AttributeError since ping() is a method only of the subclass
nginx_monitor.check()
3 months ago Permalien
cluster icon
  • Working with JSON files : Working with JSON files JSON is the standard format for data exchange in web services and cloud APIs. Python’s built-in json module provides function...
  • Adding Type Hints to Decorators and Generators : Adding Type Hints to Decorators and Generators Decorators and generators are advanced constructs that require specialized type hints to make their tr...
  • Lambda Functions : Lambda Functions Python functions defined with def allow multiple statements, clear naming, and support for docstrings, making them ideal for complex...
  • Filesystem Paths : Working with Filesystem Paths in Python Manipulating paths as plain strings is error-prone and OS-specific. pathlib provides an object-oriented, cr...
  • Python package and subpackage : Introduction to Packages (__init__.py) What is a Package? A Python package provides a way to structure a project's module namespace by using directori...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli