Classes and Objects

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn about classes and objects in Python. A class is a template for creating objects. An object is an instance of a class.

Achievements

  • Names and Objects
  • Scopes and Namespaces
  • Instance Objects
  • Method Objects
  • Inheritance
  • Private Variables

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-71{{"`Classes and Objects`"}} python/tuples -.-> lab-71{{"`Classes and Objects`"}} python/function_definition -.-> lab-71{{"`Classes and Objects`"}} python/classes_objects -.-> lab-71{{"`Classes and Objects`"}} python/constructor -.-> lab-71{{"`Classes and Objects`"}} python/polymorphism -.-> lab-71{{"`Classes and Objects`"}} python/encapsulation -.-> lab-71{{"`Classes and Objects`"}} python/raising_exceptions -.-> lab-71{{"`Classes and Objects`"}} python/build_in_functions -.-> lab-71{{"`Classes and Objects`"}} end

Defining and Creating a Class

To define a class in Python, use the class keyword followed by the name of the class.

The class definition should contain a __init__ method, which is a special method in Python that is called when an object is created from the class.

Open up a new Python interpreter.

python3

Here's an example of a class that represents a circle:

class Circle:
    def __init__(self, radius):
        self.radius = radius

The __init__ method takes in a parameter radius and assigns it to the radius attribute of the object.

Instantiating an Instance Object

To create an instance object from a class, you need to call the class name followed by parentheses. It is called an "instance" because it is a specific occurrence of the class.

circle1 = Circle(5)

This creates an instance object circle1 of type Circle with a radius of 5. Instance objects can be used to store data that is specific to the object. For example, each Circle object can have a different radius.

The __init__ method in the previous step will be called automatically when the object is created, and the radius attribute of the object will be initialized with the value 5.

The __init__ method is often used to set up the initial state of an object, such as initializing the attributes of the object or setting up connections to external resources. It is called automatically when the object is created, so you don't have to call it yourself.

It is important to note that the __init__ method is just a normal method and can have any name. However, the recommended naming convention is to use __init__ to make it clear that it is the initializer method of the class.

Accessing and Modifying Attributes

To access the attributes of an object, use dot notation. For example, to access the radius of the circle1 object, you can use the following code:

print(circle1.radius) ## Output: 5

You can modify the attributes of an object by assigning a new value to them. For example, to change the radius of the circle1 object, you can use the following code:

circle1.radius = 10
print(circle1.radius) ## Output: 10

Add Method Objects

A method is a function that is defined inside a class and is used to perform operations on the data stored in the attributes of an object. In Python, methods are defined using the def keyword followed by the method name and a list of parameters.

Here's an example of a method area defined in the Circle class:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

The area method calculates the area of a circle based on its radius. It does this by using the self.radius attribute, which refers to the radius of the object on which the method is called.

To call a method on an object, use the dot notation followed by the method name and parentheses. For example, to call the area method on the circle1 object, you can use the following code:

circle1 = Circle(15)
print(circle1.area()) ## Output: 706.5

This will print the area of the circle1 object, which is a specific instance of the Circle class.

Methods are useful for encapsulating functionality within a class and providing a way to operate on the data stored in the object's attributes.

Beginners should pay special attention to the use of parentheses. The parentheses are used to call the method on the object, and the parentheses are also used to pass in the parameters to the method. This can be confusing at first, but it will become more clear as you continue to learn about classes and objects.

Instance Objects and Method Objects are the two main types of objects in Python. In conclusion, instance objects are created from a class, and method objects are defined inside a class.

Inheritance

Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the subclass and the existing class is the superclass.

Inheritance allows you to create a subclass that has all the attributes and methods of the superclass, and you can also add additional attributes and methods to the subclass or override the attributes and methods of the superclass.

Here's an example of a subclass Cylinder that inherits from the Circle class:

class Cylinder(Circle):
    def __init__(self, radius, height):
        super().__init__(radius)
        self.height = height

The Cylinder class has a __init__ method that takes in two parameters: radius and height. It calls the __init__ method of the Circle class using the super() function to initialize the radius attribute of the object, and then sets the height attribute of the object.

The super() function is a special function in Python that refers to the superclass of a class. It is used to call methods of the superclass from within the subclass.

The super() function is defined in the class definition and takes in the self parameter, which refers to the object being created. It can also take in additional parameters depending on the method being called. In this example, It passes the radius parameter to the __init__ method of the Circle class and initializes the radius attribute of the object.

The Cylinder class now has all the attributes and methods of the Circle class, as well as the additional height attribute. You can access the attributes and methods of the Cylinder class using the dot notation, just like with the Circle class.

For example, you can create a Cylinder object and access its attributes as follows:

cylinder1 = Cylinder(5, 10)
print(cylinder1.radius)  ## prints 5
print(cylinder1.height)  ## prints 10

Inheritance is a useful feature in object-oriented programming as it allows you to reuse code and create a hierarchy of classes.

the Super() Function

The super() function is useful when you want to reuse the code from the superclass in the subclass and extend it with additional functionality.

It is important to note that the super() function is not a static reference to the superclass. It is a dynamic reference that changes depending on the class in which it is called. This allows you to use inheritance in multiple levels of inheritance and access the correct superclass at each level.

For example, consider the following classes:

class A:
    def method(self):
        print("A method")

class B(A):
    def method(self):
        super().method()
        print("B method")

class C(B):
    def method(self):
        super().method()
        print("C method")

Here, C is a subclass of B, which is a subclass of A. If you call the method method on a C object, it will first call the method method of the A class using the super() function, then the method method of the B class using the super() function, and finally the method method of the C class.

obj = C()
obj.method()  ## prints "A method", "B method", "C method"

The super() function is a useful feature in object-oriented programming that allows you to reuse code and create a hierarchy of classes.

Private Variables

In Python, private variables are variables that are intended to be used only within the class in which they are defined, and not by external code. Private variables are not directly accessible from outside the class.

To define a private variable in the Circle class, you can use the double underscore prefix (__) followed by the variable name. For example:

class Circle:
    def __init__(self, radius):
        self.__radius = radius

This defines a private variable __radius in the Circle class.

Private variables are intended to be used only within the class in which they are defined. They are not directly accessible from outside the class. For example, if you try to access the __radius variable from outside the Circle class, you will get an error:

circle1 = Circle(5)
print(circle1.__radius)  ## This will raise an AttributeError

Private variables are useful for encapsulating data within a class and limiting the ability of external code to modify it. However, it is important to note that private variables are not truly private in Python, and can still be accessed from outside the class using "name mangling".

Name mangling is a technique that involves adding a special prefix to the variable name to make it harder to access from outside the class.

For example, the __radius variable can still be accessed from outside the Circle class using the following syntax:

print(circle1._Circle__radius)  ## This will print 5

However, this is not considered a good programming practice and should be avoided.

Instead, you should use private variables only within the class in which they are defined and provide public methods to access or modify the data if necessary.

Here's an example of a Circle class with a private __radius variable and public methods to access and modify the radius:

class Circle:
    def __init__(self, radius):
        self.__radius = radius

    def get_radius(self):
        return self.__radius

    def set_radius(self, radius):
        self.__radius = radius

To access the radius of a Circle object, you can use the get_radius method:

circle1 = Circle(5)
print(circle1.get_radius())  ## prints 5

To modify the radius of a Circle object, you can use the set_radius method:

circle1.set_radius(10)
print(circle1.get_radius())  ## prints 10

Summary

In this lab, you learned about classes and objects in Python. You learned how to define a class, create an object from a class, access attributes and methods of an object, modify attributes of an object, and create a subclass that inherits from a superclass.

Here's a summary of the main concepts covered in this lab:

  • A class is a template for creating objects. An object is an instance of a class.
  • The __init__ method is called when an object is created from a class. It allows you to set the attributes of the object.
  • You can access the attributes of an object using the dot notation, and call the methods of an object using the dot notation followed by the method name and parentheses.
  • You can modify the attributes of an object by assigning a new value to them.
  • Inheritance allows you to create a subclass that is a modified version of a superclass. The subclass can override or extend the methods of the superclass.

I hope this lab helped you learn about Python classes and objects. Let me know if you have any questions!

Other Python Tutorials you may like