property decorator

'''class person:
def __init__(self,fname,lname):
self.fname=fname
self.lname=lname
self.fullname=f"{self.fname} {self.lname}" #derived from above attributes not from object arguments

p1=person("N","Harish") #object

print(p1.fullname)
p1.fname="software" #here i can change fname and lname
print(p1.fname)
print(p1.fullname) #fname changed but full name was not changed because it is not came from object arguments
'''
#_______________________________________________________________________
# using property decorator we change directly the attribute see below code

class person:
def __init__(self,fname,lname):
self.fname=fname
self.lname=lname

@property #due to this i can call fullname function as attribute that is without () after function
def fullname(self): #getter
if self.fname==None or self.lname==None:
return "fullname was deleted"
else:
return f"{self.fname} {self.lname}"
#@property has three methods that we can use 1.getter 2.setter 3.deleter

@fullname.setter #setter
def fullname(self,str): #setter
self.fname=str.split(" ")[0]
self.lname=str.split(" ")[1]

@fullname.deleter
def fullname(self): #deleter
self.fname=None
self.lname=None

p1=person("N","Harish") #object

print(p1.fullname)
p1.fname="software"
print(p1.fname)
p1.fullname="pushpa Raj"
del p1.fullname
print(p1.fullname)

Comments

Popular posts from this blog

Tokens in C

Steps taken by a compiler to execute a C program

Variables and Data Types in C