can anyone help me out with this requirement? I have been trying to fix it, but not successful. I would really appreciate if someone can help me out thanks.
name
: property - returns capitalized name and setter checks the name isalpha() and if true store the name in the object otherwise store 'Unknown'
eid
: property - returns eid zero filled up to 4 spaces and setter will assign '9999' if the length is zero, otherwise store the eid.
here is my code.
class Employee:
def __init__(self, name, eid):
self.name = name
self.eid = eid
def set_name(self, name):
if name.isalpha():
self.__name = name
else:
self.__name = 'Unknown'
def set_eid(self, eid):
if self.eid.isalpha():
self.eid = eid
else:
self.eid = "9999"
def get_name(self):
return self.name
def get_eid(self):
return self.eid
def __str__(self):
return "%s: %s " % (self.eid, self.name)
def main():
empName = input('Name')
eid = input('Id')
employeeInfo = Employee(empName, eid)
print(employeeInfo.__str__())
main()
You need to useproperty
to define a property attribute. If you want a tutorial, use Google (for example this one on Programiz ), but here's a quick example for a similar situation. If name
is not alphabetical, it's set to None
.
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name if name.isalpha() else None
boxer = Person('Clay')
print(boxer.name) # -> Clay
boxer.name = 'Ali'
print(boxer.name) # -> Ali
boxer.name = ''
print(boxer.name) # -> None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.