Python Classes/Objects
Object-oriented programming is at the heart of Python, where nearly everything is an object with properties and methods of its own.
To make objects you need a class, which acts as a constructor or "blueprint" for them.
Create a Class
The class keyword starts a new class:
Example
A class called MyClass with one property, x:
Output: complete Python program
class MyClass:
x = 5
Create Object
With MyClass defined, we can build objects from it:
Example
Make an object called p1, then print its x value:
Output: complete Python program
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
Delete Objects
The del keyword removes an object you no longer want:
Example
Remove the p1 object:
Output: complete Python program
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
del p1
# print(p1.x) # This would cause an error
Multiple Objects
A single class can produce as many objects as you like:
Note: Every object is a separate instance, so giving one object its own value for a property does not affect the others.
Example
Build three objects from MyClass:
Output: complete Python program
class MyClass:
x = 5
p1 = MyClass()
p2 = MyClass()
p3 = MyClass()
print(p1.x)
print(p2.x)
print(p3.x)
The pass Statement
Python does not allow an empty class definition. If you need one with no content for now, write the pass statement inside it and the error goes away.
Example
Output: complete Python program
class Person:
pass