Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
Creating an object (instance) of a Python class is a fundamental concept in object-oriented programming. Here's a step-by-step tutorial on how to create an object of a class in Python:
First, you need to define a class. A class is a blueprint for creating objects with specific attributes and methods. For this tutorial, let's create a simple Person
class with a __init__
method, which is a special method called when an object is created:
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'm {self.age} years old.")
To create an object (instance) of the Person
class, you need to call the class as if it were a function, passing the required arguments for the __init__
method:
person1 = Person("Alice", 30)
In this example, we created an object called person1
of the Person
class. The __init__
method of the class is called with the arguments "Alice" and 30, initializing the name
and age
attributes of the person1
object.
After creating an object, you can access its attributes and call its methods using the dot notation:
print(person1.name) # Output: Alice print(person1.age) # Output: 30 person1.greet() # Output: Hello, my name is Alice and I'm 30 years old.
You can create multiple objects (instances) of the same class, each with its own attributes:
person2 = Person("Bob", 25) print(person2.name) # Output: Bob print(person2.age) # Output: 25 person2.greet() # Output: Hello, my name is Bob and I'm 25 years old.
This tutorial covered the basics of creating objects (instances) of a Python class, initializing their attributes using the __init__
method, and accessing their attributes and methods. Understanding how to create and work with objects is essential for using object-oriented programming in Python.
Instantiating a class in Python:
class MyClass: pass # Instantiating the class my_instance = MyClass()
How to create instances of a Python class:
class MyClass: pass # Creating instances obj1 = MyClass() obj2 = MyClass()
Initializing and using class objects in Python:
__init__
method, called the constructor, which initializes the object's attributes. Objects can then be used to access or modify those attributes.class MyClass: def __init__(self, value): self.value = value # Initializing and using class objects obj = MyClass(42) print(obj.value) # Output: 42
Dynamic object creation and instantiation in Python:
class DynamicClass: def __init__(self, name): self.name = name # Dynamic object creation for i in range(3): obj = DynamicClass(f"Object-{i}") print(obj.name)