this explains setter ,getter and decorator
https://www.udemy.com/python-the-complete-python-developer-course/learn/v4/t/lecture/6022196?start=0
#getter and setter
#this program explains about the use of get and set methods and property keyword
#this class will be imported in the getsetmain.py,there is no need of importing this class
#but for the clarity and navigation purpose written as 2 programs
#set and get nethods can be used to set as well as check certain conditions
#the return variables and the assignment variable name s/b different ie..level:_lvel and lives:_lives
#if not it will result in error due to recursive
#few simple objectives like lives cannot be less than 0
#and score multiplied by 1000 for each level are achieved
class Player:
def __init__(self,name):
self.name = name
self._lives=3
self._level = 1
self._score=0
def _setlife(self,live):
if live>=0:
self._lives = live
else:
print('live cannot be negative')
self._lives=0
def _getlife(self):
return self._lives
def _setlevel(self,level):
if level>=1:
delta = level-self._level
self._score += delta * 1000
self._level = level
else:
print('level cannot be less than 1 ')
def _getlevel(self):
return self._level
lives = property(_getlife,_setlife)
level = property(_getlevel,_setlevel)
####decorator
#this is similar to the property but with different syntax
#getter
@property
def score(self):
return self._score
#setter
@score.setter
def score(self,score):
self._score = score
def __str__(self):
return("{0.name};lives:{0.lives};level:{0.level};score:{0.score}".format(self))
main program using the above imported class
#we can use getsetplayer.Player, but since it is tedious
#we have used the from and import like below
from getsetplayer import Player
tim = Player('tim')
# print(tim.name)
# print(tim.lives)
# print(tim.score)
# print(tim.level)
print(tim)
tim.lives-=1
print(tim)
tim.lives-=1
print(tim)
tim.lives-=1
print(tim)
tim.lives-=1
print(tim)
tim.lives=3
tim.level+=1
print('*********')
print(tim)
tim.level+=1
print(tim)
print('*********')
tim.score = 500
print(tim)
No comments:
Post a Comment