Python Classes and Objects

The Python classes and objects in python go in handy because a class serves as a blueprint on which an object is formed. Picture this, in reality, you go to an architect to sketch a blueprint for a structure building. The sketches structure or blueprint is the class and the erected structure is the object in python. However, as you can build many houses using a blueprint sketch, you can as well create many objects using a class in python. This page is dedicated to providing you with complete knowledge of the Python classes/Object

At the end of this page, you’ll be familiarized with the following:

  •  Python Class and Object
  • Creating python Class
  • Creating Python Objects
  • The Python Self parameter
  • Constructors in Python
  • Deleting attributes and objects in Python

You’ll be good to implement what you’ve learned after this page.

Python Classes and Objects

As stated earlier, a Python class can be compared to a blueprint on which python objects are formed. On the other hand, an object is a house built on a blueprint. In python language, an object is the collection of data or variables and functions. However, because python is an object-oriented programming language. Meaning that it focuses on objects rather than procedures.

In a relationship, an object is referred to as an instance of a class and the process of creating an object is called instantiation.

For a clear python class definition, implement the syntax:

class MyNewClass:

    ”’This is a docstring. I have created a new class”’

    pass

The docstring is not mandatory, however, it’s highly recommended.

An important point to always remember about Python objects:

  • State: It is identified by the attributes of an object and it features the properties of an object.
  • Behaviors: it’s identified by the methods of an object. it reflects the response of an object to other objects
  • Identity: it gives an object a name it also enables an object to inter-relate with others.

Important points to remember in Class

  • Classes are derived by the class keyword
  • Attributes are class variables
  • You can access the attribute of a class by using the dot(.) Operator

Creating Python Class

You create a python class by implementing the keyword class, with the syntax MyNewClass:

    ”’This is a docstring. I have created a new class”’

    pass. The attributes of a class can be either data or function. Progressively,  a new namespace where all the attributes are defined is created in a class.

The _doc_ is a special attribute that gives you the docstring of the class that is to be operated on. It’s good to note that a new object is created with the same class name once a class is created which makes it possible for easy access and instantiation.

Example:

Python Input

class Person:
    "This is a person class"
    age = 10
    def greet(self):
        print('Hello')

# Output: 10

print(Person.age)

# Output: <function Person.greet>

print(Person.greet)

# Output: "This is a person class"

print(Person.__doc__)

Output:

10
<function Person.greet>
This is a person class

Creating Python Object

An object is an instance of a class. When an object of a class is created it means that that class is instantiated. The object created shares the same attributes as a class. However, some attribute values are unique to the object only. Creating an object is similar to a function call. To access the attribute (data or methods) of an object, you should use the object’s name prefix.

Example:

Python Input:

class Person:
    "This is a person class"
    age = 10
    def greet(self):
        print('Hello')
# create a new object of the Person class
harry = Person()

# Output: <function Person.greet>

print(Person.greet)

# Output: <bound method Person.greet of <__main__.Person object>>

print(harry.greet)

# Calling object's greet() method

# Output: Hello

harry.greet()

Output:

<function Person.greet>
<bound method Person.greet of <__main__.Person object>>
Hello

Note that in a class, the object itself must be the first argument of the function which is generally called self.

The Python Self Parameter

The Python self. parameter is an explicit convention used to represent the object(instance) of a class. It’s a keyword that works to enable you to access the attributes and methods of a class in python. The focal point of the self. parameter is that it is always referencing the current object. Also, it substitutes the use of the “@” syntax in python to refer to object attributes.

The reasons for the self are held to the fact that python does not use a local variable when it reads the self.name, etc rather it uses a method or instance.

The next reason is its explicitness, you don’t need any special syntax when you explicitly call a method. And finally, Python will be cleared whether to assign an object (instance) variable or a local variable.

Click here to know more about the self parameter

Example

Python Input

# a program to prove that self and object are referring to the same object
class check:
    def __init__(self):
        print("Address of self = ",id(self))
obj = check()
print("Address of class object = ",id(obj))
# this code is Contributed by Samyak Jain

Output:


Address of self =  209
Address of class object =  209

Constructors In Python

Constructors are used to instantiate an object. This is achieved by assigning values to members of a class when an object is created. The constructor is represented by the __init__() method which is always called when an object is created. There are two types of constructors in python which are:

  • Default constructor: This type of constructor has only one argument, and it doesn’t accept any arguments.
  • Parameterized constructor: This is a constructor with parameters. This constructor values its first argument as a reference to the object of the class called self. This type of constructor accepts explicit arguments from the user.

The syntax for the Python constructor is def __init__(self):

    # body of the constructor.

Example:

Python Input

# A Sample class with init method
class Person:
    # init method or constructor
    def __init__(self, name):
        self.name = name
    # Sample Method
    def say_hi(self):
        print('Hello, my name is', self.name)
p = Person('Simon')
p.say_hi()

Output:


Hello, my name is Simon

Deleting Attributes and Objects in Python

Python enables you to delete any attributes of an object at will with the del statement. Extensively, you can delete the whole object by the same del statement

Example: deleting an attribute with the del statement

Python Input

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("Hello my name is " + self.name)
p1 = Person("Simon", 20)
del p1.age
print(p1.age)

Output:

Traceback (most recent call last):
  File https://extendsclass.com/lib/Brython-3.8.9/www/src/Lib/site-packages/editor.py, line 116, in run
    exec(src, ns)
  File <string>, line 12, in <module>
AttributeError: 'Person' object has no attribute 'age'

You have the error report because the p1.age was selected but not the entire object.

Example 2: deleting the entire object using the del statement

Python Input

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("Hello my name is " + self.name)
p1 = Person("Simon", 20)
del p1
print(p1)

Output:


Traceback (most recent call last):
  File https://extendsclass.com/lib/Brython-3.8.9/www/src/Lib/site-packages/editor.py, line 116, in run
    exec(src, ns)
  File <string>, line 13, in <module>
Exception: <Javascript TypeError>: Cannot read property '$nat' of undefined

Summary

Always remember that:

Python class can be compared to a blueprint on which python objects are formed. On the other hand, an object is a house built on the blueprint

In a relationship, an object is referred to as an instance of a class and the process of creating an object is called instantiation.

An important point to always remember about Python objects:

  • State: It is identified by the attributes of an object and it features the properties of an object.
  • Behaviors: it’s identified by the methods of an object. it reflects the response of an object to other objects
  • Identity: it gives an object a name it also enables an object to interrelate with others.

Important points to remember in Class

  • Classes are derived by the class keyword
  • Attributes are class variables
  • You can access the attribute of a class by using the dot(.) Operator

At the end of this page, you are familiarized with the following:

  •  Python Class and Object
  • Creating python Class
  • Creating Python Objects
  • The Python Self parameter
  • Constructors in Python
  • Deleting attributes and objects in Python

Go on, give it all the effort needed to be good at it. Be sure to put all your knowledge to work by practice. For a helping hand see the Python Tutorials. Good luck coding!

Hi, I’m Pramod Kumar Yadav & a computer science Engineer with 3years of experience in Digital marketing. I’m self-motivated and love to do SEO.




Best PYthon Course

Get More trending Courses

Leave a Reply

%d bloggers like this: