HomeToolsAbout

Class

What is it

Python is Object Oriented language Class is an object constructor or a "blueprint" for creating objects

Syntax

Creation

Creating a Class; created class named MyClass with property x

class MyClass: x = 5

Instantiation

Creating an object; created an object name class_one using MyClass and printed the property of x

class_one = MyClass() print(class_one.x) # 5

Init Constructor

__init__

All functions have class called __init__() which is always executed when class is initiated

Use the __init__() function to assign values to object properties. It also requires self to be passed as a first parameter

class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) # "John" print(p1.age) # 36

Methods in objects are functions that belong to the object

classPerson: 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()

Self keyword

The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class

classPerson: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is "+ abc.name) p1 = Person("John",36) p1.myfunc()

Modifying the instantiated object

Modify Object Properties through literal assignment

p1.age =40

Deleting object or properties

del p1.age # deletes age property del p1 # deletes the p1 object
AboutContact