w3resource

What is a Python class? Define a class with an example.

Python Classes: Definition and Example

A "class" in Python is a blueprint or template for creating objects. It defines a set of attributes (variables) and methods (functions) common to all objects of that class. The purpose of a class is to serve as a blueprint for creating multiple instances (objects) that share the same characteristics and behaviors.

Compared with other programming languages, Python's class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of C++ and Modula-3 class mechanisms. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.

Here's an example of how to define a simple class in Python:

class Cat:

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def bark(self):
        return "Miu! Miu!"
    def get_age(self):
        return self.age
    def set_age(self, new_age):
        self.age = new_age

In the above example, we defined a class called "Cat". It has attributes 'name' and 'age', along with methods 'bark', 'get_age', and 'set_age'. The 'init' method is a special constructor method that initializes the attributes when a new instance of the class is created.

Now we can create objects (instances) of the "Cat" class and access their attributes and methods like this:

cat1 = Cat("Coco", 4)
print(cat1.name)  # Output: Coco
print(cat1.bark())  # Output:Miu! Miu!
cat2 = Cat("Kiki", 2)
print(cat2.get_age())  # Output: 2
cat2.set_age(6)
print(cat2.get_age())  # Output: 6

Each object created from the "Cat" class will have its own distinct 'name' and 'age', but they all share the same methods defined in the class. Python classes are essential for implementing Object-Oriented Programming concepts and organizing code into reusable and maintainable units.



Follow us on Facebook and Twitter for latest update.