“class” Keyword in Python: Object-Oriented Programming Made Simple

"class" Keyword in Python: Object-Oriented Programming Made Simple

If you’re new to object-oriented programming, one of the concepts that you’ll often encounter in Python is the “class” keyword.

Classes are one of the fundamental concepts in object-oriented programming, allowing you to define your own custom types and create objects that encapsulate data and behavior. In Python, everything is an object, and so understanding classes and how to create them is a critical component of becoming proficient in Python.

In this tutorial, we’ll explore the class keyword in Python and learn how to define classes, create objects, and use those objects to store data and invoke methods.

Creating a Class

Creating a class in Python is straightforward. The basic syntax for creating a class is:

class MyClass:
    pass

In this example, we’re creating a class called MyClass. We’re not defining any attributes or methods for this class yet, so we’re using the “pass” keyword to indicate that there’s no code to execute yet.

The name of the class should be in CamelCase. This means that the first letter of each word should be capitalized.

Let’s create another example:

class Person:
    pass

In this case, we’ve created a class called Person. This will be a generic representation of a person. We haven’t defined any attributes or methods for this class yet, but we’ll do that in the next section.

Defining Attributes and Methods

Once you’ve created a class, the next step is to define its attributes and methods. Attributes are the data that’s attached to an object. Methods, on the other hand, are the functions that you can call on an object in order to manipulate its data or execute some other behavior.

Let’s define some attributes for our “Person” class:

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

The “init” method is a special method that’s called when you create a new object of a class. It’s the constructor of the class. “self” refers to the object itself. We’re using “self.name” and “self.age” to define two attributes for our Person class.

The attribute “name” is the name of the person, and “age” is their age. We’ve passed these values into the “init” method when we created a new object.

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

p = Person("John", 20)
print(p.name)
print(p.age)

The output of this code will be:

John
20

In this example, we’ve created a new object of our “Person” class called p. We’ve passed in two values, “John” and 20, for the name and age attributes of our object. We then printed out these values to show that they were successfully assigned.

Let’s define the methods for our “Person” class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")

In this example, we’ve defined a new method called “say_hello”. This method takes no arguments other than the “self” parameter, which refers to the object itself.

Inside the “say_hello” method, we’re constructing a string that consists of the name and age attributes of the object. We then use the “print” function to output this string to the console.

Let’s create a new object of our “Person” class and invoke the “say_hello” method:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")

p = Person("John", 20)
p.say_hello()

The output of this code will be:

Hello, my name is John and I am 20 years old.

Encapsulation

One of the primary benefits of object-oriented programming is the concept of encapsulation. Encapsulation means that the data and behavior of an object are hidden from the outside world, and can only be accessed through the methods of the object. This provides a layer of abstraction and allows you to control how your objects are used.

In Python, encapsulation can be achieved by using the double underscore “__” prefix on an attribute or method. This means that the attribute or method is private and cannot be accessed from outside the object.

Let’s modify our “Person” class to use encapsulation:

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age
    
    def say_hello(self):
        print("Hello, my name is " + self.__name + " and I am " + str(self.__age) + " years old.")

We’ve modified our “Person” class to use double underscore prefixes on the “name” and “age” attributes. This means that they’re now private and cannot be accessed from outside of the object.

Let’s create a new object of our “Person” class and try to access the “name” and “age” attributes from outside the object:

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age
    
    def say_hello(self):
        print("Hello, my name is " + self.__name + " and I am " + str(self.__age) + " years old.")

p = Person("John", 20)
print(p.__name)
print(p.__age)

The output of this code will be:

AttributeError: 'Person' object has no attribute '__name'

In this example, we’ve created a new object of our “Person” class called p. We’ve then tried to access the “name” and “age” attributes from outside the object, but we’ve received an AttributeError. This is because those attributes are now private and cannot be accessed from outside the object.

Inheritance

Inheritance is another fundamental principle of object-oriented programming. It allows you to create new classes that inherit the attributes and methods of an existing class. This makes it easy to create more specialized classes that have their own unique behavior but also share common behavior with other classes.

In Python, inheritance is achieved by specifying the parent class in the child class definition:

class ParentClass:
    def __init__(self, value):
        self.value = value
        
    def get_value(self):
        return self.value

class ChildClass(ParentClass):
    def get_value_plus_one(self):
        return self.value + 1

In this example, we’ve defined a parent class called “ParentClass”. It has an init method that takes a single value and a “get_value” method that returns that value. We’ve then defined a child class called “ChildClass” that inherits from the ParentClass. It has a new method called “get_value_plus_one” that returns the parent value incremented by one.

Let’s create a new object of the “ChildClass” and invoke its methods:

class ParentClass:
    def __init__(self, value):
        self.value = value
        
    def get_value(self):
        return self.value

class ChildClass(ParentClass):
    def get_value_plus_one(self):
        return self.value + 1

c = ChildClass(5)
print(c.get_value())
print(c.get_value_plus_one())

The output of this code will be:

5
6

In this example, we’ve created a new object of the “ChildClass” called “c”. We’ve passed in a value of 5 to the constructor of the object. We then printed out the value using the “get_value” method and printed out the incremented value using the “get_value_plus_one” method.

Conclusion

In conclusion, the “class” keyword is an essential component of object-oriented programming in Python. Classes allow you to define your own custom types and create objects that encapsulate data and behavior. Attributes are the data that’s attached to an object and methods are the functions that you can call on an object in order to manipulate its data or execute some other behavior.

We’ve explored how to create a new class, define attributes and methods, use encapsulation to hide data, and inherit from an existing class. By mastering these concepts, you’ll be well on your way to becoming a proficient Python programmer.

Leave a Reply

Your email address will not be published. Required fields are marked *