↓ Skip to main content
Python

Python: Class

·1 min

Learning to write Python code? A Python class is a blueprint for creating objects.

It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        print("Woof!")

The class keyword is used to define a new class. The name of the class is Dog.

The __init__ method is a special method in Python that is used to initialize an object when it is created. The self parameter refers to the instance of the object being created.

The name and breed attributes are created within the __init__ method and can be accessed using the self reference.

The bark method is an example of a custom method in the class. It can be called on an instance of the Dog class to print “Woof!”.

To create an instance of the class, you can use the following code:

dog = Dog("Fido", "Labrador")
dog.bark()
# Output: Woof!

This creates a new instance of the Dog class, with the name attribute set to “Fido” and the breed attribute set to “Labrador”.

The bark method is then called on the dog instance to produce the output “Woof!”.

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Decorators

·1 min
Let’s learn about decorators @iamdecorator Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Python: Inheritance

·2 mins
Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.

Python: Interface

·1 min
n Python, unlike some other programming languages, there is no explicit syntax for defining interfaces. However, you can create a similar concept by defining an abstract base class (ABC) that contains abstract methods. An abstract method is a method that is declared in a base class, but has no implementation. Subclasses of the abstract base class must implement these abstract methods.