Python Classes And Objects
Python is an Object-Oriented Programming Language which means almost everything in Python are based on the concept of objects that can contain data in the form of fields and properties and code in the form of methods.
A class is a blueprint for creating objects.
Create Python Class
The class keyword is used to create a class in Python.
Create a class Dog with a single String type property color with value Brown:
class Dog: color = "Brown"
Create Python Object
An object in Python, is created from a class.
Create an object of the Dog class:
class Dog: color = "Brown" dog = Dog() print(dog.color)
The __init__() Function / Class Constructor
The __init__() function is a built-in Python function. Every class in Python has the __init__() function and is executed while creating an object of a class.
The __init__() function is used as a constructor of the class to initialize properties of the class or to perform other operations that needs to be executed while creating an object.
class Customer: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age customer = Customer("Danny", "Charm", 26) print(customer.firstname) print(customer.lastname) print(customer.age)
The self Parameter
The self parameter is used to represent the current instance of the class which helps to access properties and methods of the class.
A method is a block of code or function that belongs to an object. Methods can only be called after creating objects.
Create Object Methods
Object methods are created inside the body of a class using the def keyword followed by the method name and parenthesis as shown in the example below:
class Calculator: def add(self, x, y): result = x + y return result def substract(self, x, y): result = x - y return result def multiply(self, x, y): result = x * y return result def divide(self, x, y): result = x / y return result cal = Calculator() a = cal.add(115,6) b = cal.substract(190, 100) c = cal.multiply(5, 5) d = cal.divide(100, 16) print("Addition is " + str(a)) print("Substraction is " + str(b)) print("Multiplication is " + str(c)) print("Division is " + str(d))
Substraction is 90
Multiplication is 25
Division is 6.25