Python class topic and tips
Python class topic and tips
init Method: This is the constructor method, called automatically when an object is created. It’s used to
initialize the object’s state.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
2. Self Parameter:
The self parameter refers to the instance calling the method. It allows access to the instance’s attributes
and methods within the class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
class Dog:
species = "Canis lupus familiaris" # Class attribute
4. Method Types:
Instance Methods: Take self as the first parameter and can modify object state.
Class Methods: Take cls as the first parameter and can modify class state. Use the @classmethod
decorator.
Static Methods: Don’t modify object or class state. Use the @staticmethod decorator.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
class Dog:
species = "Canis lupus familiaris"
@classmethod
def species_info(cls): # Class method
return f"This species is {cls.species}"
@staticmethod
def general_info(): # Static method
return "Dogs are loyal pets."
5. Inheritance:
Inheritance allows you to define a class that inherits all the methods and properties from another class.
This promotes code reusability.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
6. Understanding super():
The super() function allows you to call methods from the parent class, which is especially useful in
inheritance.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
class Puppy(Dog):
def __init__(self, name, age):
super().__init__(name, age) # Call the parent class constructor
7. Encapsulation:
Encapsulation restricts direct access to some of an object’s components. In Python, you can denote
private attributes by prefixing them with an underscore (_).
In [23]:
class Dog:
def __init__(self, name, age):
self._name = name # "Protected" attribute
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Dog(name={self.name}, age={self.age})"
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
def __init__(self, name, toys=None):
self.name = name
self.toys = toys or []
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
return self.engine.start()
tutorial@point
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF