classPerson:Name=""Age=""def__init__(self,name,age):print("New person class created")self.Name=nameself.Age=age@staticmethoddefSayHello():print("Hello Sir")p=Person("Vivek",31)Person.SayHello()
Class with constructor
Python can have only one constructor, so if you create multiple method with __init__ python will only use last one
classPerson:Name=""Age=""def__init__(self,name,age):print("New person class created")self.Name=nameself.Age=agedefPrintData(self):print(f"Name:{self.Name}")print(f"Age:{self.Age}")p=Person("Vivek",31)p.PrintData()
To use multiple instructor use classmethod decorator
classPerson:Name:(str)Age:(int)def__init__(self):self.Name="Vivek"self.Age=31print("New person class created")@classmethoddeffrom_name(cls,name):person=cls()person.Name=nameperson.Age=31returnperson@classmethoddeffrom_name_age(cls,name,age):person=cls()person.Name=nameperson.Age=agereturnpersondef__str__(self):returnf"Hey my name is {self.Name}. I am {self.Age} year old"p=Person()print(p)p=Person.from_name("Vivek")print(p)p=Person.from_name_age("Vivek",31)print(p)
classPerson:Name=""Age=""def__init__(self):print("New person class created")def__init__(self,name,age):print("New person class created")self.Name=nameself.Age=agedefPrintData(self):print(f"Name:{self.Name}")print(f"Age:{self.Age}")classEmployee(Person):Salary=10000Company="Microsoft"defPrintData(self):super().PrintData()print(f"Age:{self.Company}")print(f"Age:{self.Salary}")p=Employee("Vivek",31)p.PrintData()
Create list using custom class
classPoint:# constructordef__init__(self,x,y):self.x=xself.y=y# method to calculate distance from origindefdistance_from_origin(self):return(self.x**2+self.y**2)**0.5# method to calculate distance from another pointdefdistance_from_point(self,other):return((self.x-other.x)**2+(self.y-other.y)**2)**0.5# method to print the point coordinatesdef__str__(self):returnf"({self.x}, {self.y})"# creating list of pointpoints=[]foriinrange(1,11):point=Point(i,2*i)points.append(point)forpointinpoints:print(point)