Object-Oriented Programming in Python
Python is an object-oriented programming language. This means that it provides features that support object-oriented programming (OOP).
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
Creating a Class
class MyClass:
x = 5
Creating an Object
p1 = MyClass()
print(p1.x)
The __init__() Function
The __init__() function is a special function that is called when an object is created. It is used to initialize the object's state.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Methods
Methods are functions that belong to an object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()