Tutorial

Class, Objects in Python

10 min read

Classes in Python

In Python, classes are a fundamental feature of object-oriented programming (OOP). They allow you to define a blueprint or template for creating objects, which can have attributes (variables) and methods (functions). To create a class in Python, we use the class keyword followed by the name of the class. For example:

class MyClass:
    pass

This defines a class called MyClass with no attributes or methods. We can then create instances of this class by calling the class name as if it were a function:

obj = MyClass()

We can also define attributes and methods for the class using the def keyword:

class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}!")

obj = MyClass("Alice")
obj.greet()  # Output: Hello, Alice!

Here, we define a constructor method (__init__) that takes a name parameter and initializes an instance variable self.name with it. We also define a greet method that prints a greeting using the self.name variable.

One important concept in OOP is inheritance, where we can create a new class that inherits attributes and methods from an existing class.

For example:

class MySubclass(MyClass):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

    def greet(self):
        print(f"Hello, {self.name}! You are {self.age} years old.")

obj = MySubclass("Bob", 30)
obj.greet()  # Output: Hello, Bob! You are 30 years old.

Here, we define a subclass MySubclass that inherits from MyClass.

We define a new constructor that takes an additional age parameter and initializes an instance variable self.age with it. We also override the greet method to include the self.age variable.

Objects in Python

In Python, an object is an instance of a class. When we create a new object, we are creating a new instance of that class with its own unique set of attributes and methods. Objects are the basic building blocks of object-oriented programming in Python.

To create an object in Python, we first need to define a class. We can do this using the class keyword, followed by the name of the class and any attributes and methods we want to include:

class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}!")

Here, we define a class called MyClass with a constructor method (__init__) that takes a name parameter and initializes an instance variable self.name with it. We also define a greet method that prints a greeting using the self.name variable.

To create an object of this class, we simply call the class name as if it were a function, passing in any parameters required by the constructor:

obj = MyClass("Alice")

This creates a new object for the MyClass class with a name attribute set to "Alice".

We can then access this attribute using dot notation:

print(obj.name)  # Output: Alice

We can also call methods on the object using dot notation:

obj.greet()  # Output: Hello, Alice!

Objects in Python are dynamically typed, which means that their type can change at runtime.

For example, we can create a new object and assign it to a variable:

obj = MyClass("Alice")

We can then assign a new object of a different class to the same variable:

obj = SomeOtherClass()

This re-assigns the obj variable to a new object of a different class, effectively changing its type. This flexibility is one of the strengths of Python’s object-oriented programming model.

Access Class Attributes Using Objects in Python

In Python, we can access class attributes using objects. Class attributes are variables that are defined at the class level and are shared by all instances of the class. To access a class attribute using an object, we use dot notation, just like we would with an instance attribute.

For example, let’s say we have a class called Person with a class attribute called species:

class Person:
    species = 'human'

    def __init__(self, name):
        self.name = name

Here, we define a class called Person with a class attribute species set to 'human'. We also define a constructor method that takes a name parameter and initializes an instance variable self.name with it.

To access the species attribute using an object, we simply use dot notation:

p = Person('Alice')
print(p.species)  # Output: human

In this example, we create a new object of the Person class with a name attribute set to "Alice". We then access the species attribute using dot notation, which returns the value "human".

We can also modify class attributes using objects. When we modify a class attribute using an object, it only affects that object – other objects of the same class will still have the original value of the attribute.

For example:

p = Person('Alice')
print(p.species)  # Output: human

p.species = 'alien'
print(p.species)  # Output: alien

q = Person('Bob')
print(q.species)  # Output: human

Here, we create a new object p of the Person class and modify its species attribute to "alien". When we print the species attribute using p, we get "alien". However, when we create a new object q of the same class and print its species attribute, we get the original value of "human".

Create Multiple Objects of Python Class

In Python, we can create multiple objects of a class. Each object is an instance of the class and has its own set of attributes and methods. To create multiple objects of a class, we simply call the class constructor multiple times with different arguments.

For example, let’s say we have a class called Person:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

In this example, we define a class called Person with a constructor method that takes name and age parameters and initializes instance variables self.name and self.age with them. We also define a greet method that prints a greeting using the self.name and self.age variables.

To create multiple objects of this class, we simply call the constructor multiple times with different arguments:

p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p3 = Person("Charlie", 35)

Here, we create three objects p1, p2, and p3 of the Person class with different name and age attributes. Each object has its own set of attributes and methods and can be manipulated independently.

We can then call methods on each object using dot notation:

p1.greet()  # Output: Hello, my name is Alice and I am 25 years old.
p2.greet()  # Output: Hello, my name is Bob and I am 30 years old.
p3.greet()  # Output: Hello, my name is Charlie and I am 35 years old.

Here, we call the greet method on each object, which prints a greeting using the name and age attributes specific to each object.

Python Methods

In Python, methods are functions that are defined inside a class and are associated with an object of that class. Methods can access and manipulate the attributes of the object, and can also access other methods of the same object or other objects of the same class.

Methods in Python are defined using the def keyword, just like regular functions, but they are defined inside a class.

For example, let’s say we have a class called Person with a method called greet:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, my name is {self.name}.")

Here, we define a class called Person with a constructor method that takes a name parameter and initializes an instance variable self.name with it. We also define a method called greet that prints a greeting using the self.name variable.

To call the greet method on an object of this class, we simply use dot notation:

p = Person("Alice")
p.greet()  # Output: Hello, my name is Alice.

Here, we create an object p of the Person class with a name attribute set to "Alice". We then call the greet method on p, which prints a greeting using the name attribute of p.

Methods in Python can also take parameters, just like regular functions.

For example, let’s say we have a method called change_name that takes a new name and updates the name attribute of the object:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, my name is {self.name}.")

    def change_name(self, new_name):
        self.name = new_name

Here, we define a method called change_name that takes a new_name parameter and updates the name attribute of the object using the self keyword.

To call the change_name method on an object, we simply pass the new_name parameter:

p = Person("Alice")
p.greet()  # Output: Hello, my name is Alice.

p.change_name("Bob")
p.greet()  # Output: Hello, my name is Bob.

Here, we create an object p of the Person class with a name attribute set to "Alice".

We then call the greet method on p, which prints a greeting using the name attribute of p. We then call the change_name method on p with a new_name parameter of "Bob", which updates the name attribute of p. We then call the greet method on p again, which prints a greeting using the updated name attribute of "Bob".

Constructors in Python

In Python, a constructor is a special method that is automatically called when an object of a class is created. The purpose of a constructor is to initialize the instance variables of the object with values passed as arguments, or with default values.

In Python, the constructor method is called __init__() and is defined within the class definition. Here’s an example of a class with a constructor:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Here, we define a class called Person with a constructor method that takes two parameters: name and age. Inside the constructor, we initialize two instance variables using the values of the parameters.

To create an object of this class, we simply call the class name with the required parameters:

p = Person("Alice", 25)

Here, we create an object p of the Person class with a name attribute set to "Alice" and an age attribute set to 25. The constructor method __init__() is automatically called with the arguments "Alice" and 25, and initializes the instance variables self.name and self.age with those values.

If we want to initialize instance variables with default values, we can define a constructor that takes no parameters and initializes the variables with the default values. Here’s an example:

class Person:
    def __init__(self):
        self.name = "Unknown"
        self.age = 0

In this example, we define a class called Person with a constructor method that takes no parameters. Inside the constructor, we initialize two instance variables self.name and self.age with default values.

To create an object of this class, we simply call the class name without any parameters:

p = Person()

Here, we create an object p of the Person class with a name attribute set to "Unknown" and an age attribute set to 0. The constructor method __init__() is automatically called with no arguments, and initializes the instance variables self.name and self.age with the default values.

Overall, constructors in Python are a powerful tool for initializing the instance variables of an object with values passed as arguments or with default values. By defining constructors within a class and calling them when objects are created, we can create more flexible and dynamic programs.