Skip to content

Python create object

  • by

Python object is created after creating a class. Instant of the object is created using the name same as the class name and it is known as Object Instantiation.

object_name = class_name()

class – A user-defined blueprint for an object that combines a set of attributes that describes the properties of that object.

Data members – It is a class variable or instance variable that holds properties associated with a class and its objects.

self – This is a default parameter in every method in a class, even if we have no arguments to pass.

__init__ – The __init__ represents constructor in python. this is used to initialize the object’s state.

Method – It is a user-defined function that can be defined inside or outside a class definition. It also contains a set of statements to execute

Python creates object example

Simple example code.

class Dog:
# data members of class
color = "black" # attribute 1
name = "Polo" # attribute 2

# class default constructor
def __init__(self, name, color):
self.name = name
self.color = color

# user defined function of class
def func(self):
print("After calling func() method..")
print("My dog's name is", self.name)
print("His color is", self.color)


# object 1 is created and default constructor is called
obj1 = Dog('Robert', 'white')

# user-defined function is called from object 1
obj1.func()

# access the attribute
print(obj1.name)

Output:

Python create object

Another example

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

How can I create an object and add attributes to it?

Generally, just do this:

class Object(object):
    pass

a = Object()
a.somefield = somevalue

Do comment if you have any doubts or suggestions on this Python object topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading