Property And Setter Method

class Person :

def __init__(self,fname,lname):
self.fname = fname
self.lname = lname
self.email = f"{fname}.{lname}@gmail.com"

def printname(self):
return f"The Person Name Is {self.fname} {self.lname}"

harrypotter = Person("Harry","Potter")
print(harrypotter.fname)
print(harrypotter.lname)
print(harrypotter.email)

harrypotter.fname = "A" # If you tried to change the fname it will not change its email #
print(harrypotter.email) # Email will be same #


''' If you want to change email with the change in its fname and lname
Then you have to define a Method '''

# Let's See #

class Person :

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

def printname(self):
return f"The Person Name Is {self.fname} {self.lname}"

@property # To call the function with the help of Attribute,We use property method #
def email(self): # Method #
return f"The Email Is {self.fname}.{self.lname}@gmail.com"

@email.setter # setter method = Used to set an email#
def email(self,string):
list = string.split("@")
names = list[0]
self.fname = names.split(".")[0]
self.lname = names.split(".")[1]

@email.getter # getter method = Used to get an email #
def email(self):
if self.fname == None or self.lname == None :
return "Email is not set , Please set it using setter method"
return f"The Email Is {self.fname}.{self.lname}@gmail.com"

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

harrypotter = Person("Harry","Potter")
print(harrypotter.fname)
print(harrypotter.lname)
print(harrypotter.email) # Function is called with the help of Attribute because we have used property method #

harrypotter.fname = "H"
harrypotter.lname = "P"
print(harrypotter.email) # fname and lname is changed with the help of method #


''' For Ex. If you tried to change an Attribute It will throw an error,
If you want to change It you have to use setter method '''
harrypotter.email = "Captain.America@gmail.com" # Show ERROR without setter #
print(harrypotter.email)

del harrypotter.email # To delete an email you have to define a deleter method #
print(harrypotter.email)

Comments

Popular posts from this blog

Python Program To Store Marks

Currency.txt

Python Comprehensions