Python Classes
Python Classes/Objects
Creating classes and objects
Python Classes/Objects
Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods.
Create a Class
To create a class, use the keyword class:
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects:
p1 = MyClass()
print(p1.x)
The __init__() Function
All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)