training day7
Classes In Python
Constructor in python by default it is pre- defined that is __init__( )
Example :
class persons:
def __init__(self,name,age);
self.name = name
self.age = age
p1 = persons("John",30)
print(p1.name)
print(p1.age)
Self is the reference to current instance of class. We can access variables belonging to class using self keyword.
Example :
def __init__(self,name,age):
self.name = name
self.age = age
def myfunction(self):
print("Hello! my name = " + self.name + " and age = " + self.age)
p1.persons("John",30)
p1.myfunction()
we can write anything instead of self, but first parameter will always be a the instance.
If we want to delete any variable from class
class person:
def __init__(self,name,age):
self.name = name
self.age = age
def myfunction(self):
print("Hello,my name is " + self.name +" and age = " " + self.age"))
p1 = person("John",30)
del p1.age
p1.myfunction( )
Comments
Post a Comment