Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
Now Reading
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Are you prepared to advance your Python knowledge? If so, learning about Python objects and classes is a good way to start. They are the foundation for numerous projects. Learning about objects makes coding much more than just adding numbers or printing strings - it becomes an exercise in making something substantial from separate components.
Read on this Python objects guide to learn what is an Object in Python, the fundamental concepts of objects, the different properties of an object, and how a class is defined and an object is created.
An object is the core building block of the language, representing real-world entities or abstract concepts. Objects are instances of classes defining their structure and behavior. They encapsulate data as attributes and functionality as methods. Let's understand the objects to model and implement complex systems in Python and create custom data types and functionalities.
An object is a subclass of a class. It is a set of characteristics (variables) and methods. To do actions, we need a class object. Objects have two distinct characteristics: They have states and behaviors (an object has properties and methods connected to it). Its attributes indicate its state, and its methods represent its behavior. We can modify its state by using its methods.
Each object possesses the following attributes.
Here's an example to illustrate the classes and objects in Python concept:
Example 1
# Define a class called "Person."
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 am {self.age} years old.")
# Create two Person objects
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Access object attributes and call object methods
print(person1.name) # Output: "Alice"
person2.greet() # Output: "Hello, my name is Bob, and I am 25 years old.
Example 2
class Person:
name=""
age=0
city=""
def display(self):
print("Name: ", self.name)
print("Age: ", self.age)
print("City: ", self.city)
# Create the first Person object p1
p1 = Person()
p1.name = "Rahul"
p1.age = 20
p1.city = "Kolkata"
# Call the display method to print p1's attributes
p1.display()
print()
# Create the second Person object p2
p2 = Person()
p2.name = "Karan"
p2.age = 22
p2.city = "Bangalore"
# Call the display method to print p2's attributes
p2.display()
print()
# Call the display method for p1 again
p1.display()
It demonstrates each string object in Python created from the Person class maintains its attribute values, which are independent of other objects. Here's the output based on the code:
Name: Rahul
Age: 20
City: Kolkata
Name: Karan
Age: 22
City: Bangalore
Name: Rahul
Age: 20
City: Kolkata
As shown in the output, p1 and p2 have their own distinct values for the name, age, and city attributes. When you call the display method for p1 again at the end, it displays the values associated with p1, demonstrating using objects in Python data is independent.
Understanding using objects in Python and their relationships is fundamental to creating a well-structured, maintainable, and flexible code. Here are the core concepts of Python class(object) vs class, instances, attributes, and methods. Let's dive deeper to know what is a class in Python with an example:
1. What is a class in Python:
Classes are blueprints for objects, defining their structure and behavior. Consider a Car class:
Class in Python with an example
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
return f"{self.make} {self.model}'s engine started."
2. Instances:
Instances are individual objects created from a class. You can create multiple car instances with unique attributes:
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
3. Attributes:
Attributes are variables that hold data specific to each instance. In this case, make and model are attributes of car instances:
print(car1.make) # Output: "Toyota"
print(car2.model) # Output: "Civic"
4. Methods:
Methods are functions defined within the class, allowing objects to perform actions. Here, start_engine is a method:
print(car1.start_engine()) # Output: "Toyota Camry's engine started."
print(car2.start_engine()) # Output: "Honda Civic's engine started."
5. Inheritance:
Python supports inheritance, where one class can inherit attributes and methods from another. For example, you can create an ElectricCar class that inherits from Car:
class ElectricCar(Car):
def __init__(self, make, model, battery_capacity):
super().__init__(make, model)
self.battery_capacity = battery_capacity
def describe_battery(self):
return f"{self.make} {self.model} has a {self.battery_capacity} kWh battery."
6. Polymorphism:
Python supports polymorphism, treating different classes as instances of a common base class. This allows for flexibility in code design and usage:
def get_vehicle_description(vehicle):
return f"{vehicle.make} {vehicle.model}"
vehicle1 = Car("Ford", "Mustang")
vehicle2 = ElectricCar("Tesla", "Model S", 85)
print(get_vehicle_description(vehicle1)) # Output: "Ford Mustang"
print(get_vehicle_description(vehicle2)) # Output: "Tesla Model S"
7. Constructor (__init__):
The __init__ method initializes object attributes when the object is created. It is called automatically when creating an object.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
dog1 = Dog("Buddy," "Golden Retriever")
In Python, you can create objects of a class by following these steps:
Here's an example to illustrate how to create an object in Python in steps:
# Step 1: Define a Class
class Cat:
# Constructor method
def __init__(self, name, age):
self.name = name
self.age = age
# Method to make the cat meow
def meow(self):
print(f"{self.name} say Meow!")
# Step 2: Instantiate Objects
cat1 = Cat("Whiskers", 5)
cat2 = Cat("Fluffy", 3)
# Step 3: Access Attributes and Methods
print(f"{cat1.name} is {cat1.age} years old.")
print(f"{cat2.name} is {cat2.age} years old.")
cat1.meow()
cat2.meow()
Output:
Whiskers is 5 years old.
Fluffy is 3 years old.
Whiskers say Meow!
Fluffy says Meow!
class Circle:
pi = 3.14159 # Class attribute
def __init__(self, radius):
self.radius = radius
def area(self):
return self.pi * self.radius**2
# Create an object of the Circle class
circle1 = Circle(5)
# Access class attribute and call class method using the object
print(circle1.pi) # Access class attribute
print(circle1.area()) # Call class method
class Student:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
def introduce(self):
return f"My name is {self.name}, and I am {self.age} years old."
# Create an object of Student class
student1 = Student("Alice", 20)
# Access instance attributes and call instance method using the object
print(student1.name) # Access instance attribute
print(student1.introduce()) # Call instance method
class Vehicle:
fuel_type = "Petrol" # Class attribute
def __init__(self, make, model):
self.make = make # Instance attribute
self.model = model # Instance attribute
def info(self):
return f"This {self.make} {self.model} runs on {self.fuel_type}."
# Create an object of the Vehicle class
car = Vehicle("Toyota," "Camry")
# Access class attributes, instance attributes, and call an instance method
print(car.fuel_type) # Access class attribute
print(car.make) # Access instance attribute
print(car.info()) # Call instance method
In Python, SELF is a default variable that holds the memory address of the current object. The self-variable can relate to instance variables and methods. When a class object is formed, its object name contains the object's memory address. Because SELF knows the memory address of the object, this memory location is introduced to it internally. Thus, the variable and method of an object are accessible. Because the first parameter to any object method is always an object reference, the first argument is always SELF. Whether you call it or not, this procedure occurs automatically.
Here's an example demonstrating the use of the SELF variable in a class:
class MyClass:
def __init__(self, value):
self.value = value # Instance attribute
def display(self):
print(f"The value is: {self.value}")
def update_value(self, new_value):
self.value = new_value
# Create an object of MyClass
obj = MyClass(42)
# Access instance attribute and call instance method using the object
obj.display() # Output: The value is: 42
# Call a method that updates the instance attribute
obj.update_value(100)
# Access the updated instance attribute
obj.display() # Output: The value is: 100
In Python, you can modify an object's properties (attributes) by using the object's reference and the dot notation to access and update those attributes. Here's how you can do it:
You can directly assign new values to an object's attributes using the object reference and dot notation. Here's an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create an object of Person class
person = Person("Alice", 25)
# Modify attributes
person.name = "Bob"
person.age = 30
# Access the modified attributes
print(person.name) # Output: Bob
print(person.age) # Output: 30
You can also create methods within the class to update the object's attributes. This is done to encapsulate the logic for updating attributes. Here's a Python classes and objects exercises example:
class BankAccount:
def __init__(self, account_number, balance):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance = amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient balance.")
# Create an object of BankAccount class
account = BankAccount("12345", 1000)
# Use methods to deposit and withdraw
account.deposit(500)
account.withdraw(300)
# Access the updated balance
print(account.balance) # Output: 1200
In Python, you can delete an object using the del statement. The del statement removes a reference to an object, allowing the Python garbage collector to reclaim the memory used by the object when there are no more references to it. Here's how you can delete an object:
class MyClass:
def __init__(self, value):
self.value = value
# Create an object of MyClass
obj = MyClass(42)
# Delete the object using the 'del' statement
del obj
# Attempting to access 'obj' after deletion will result in an error
# Uncommenting the line below will raise a NameError
# print(obj)
In Python, objects are instances of classes, and they are the building blocks of the language. Objects encapsulate data and behavior to model real-world entities and implement complex systems. Understanding objects and how to work with them is fundamental to Python programming.
1: Are objects in Python similar to variables?
Objects and variables are related but different concepts. A variable is a name that references an object in memory. Objects are the actual data structures that hold the values and have associated behavior.
2: Can I create multiple objects from the same class?
Yes, you can create multiple objects from the same class. Each object is independent and has its own attributes, and can call the class's methods.
3: What is an object () in Python?
The object () is used to construct an object with no features. The object created has all of the methods and attributes used as the foundation for all the classes in the code.
4: What is an instance variable?
Instance variables are values assigned within the init method (constructor) or method with self.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...