I'm need everyone here advise to guide me, I'm trying to a class in Python OOP, this is my below code. I already import abstractmethod but not sure why there's error below. I don't understand how to resolve this.. Can anyone help me out?
from abc import ABC, abstractmethod
class Employee(ABC):
def __init__(self, employeeId, name, workFromHome, leaveBalance = 0):
self._employeeId = employeeId
self._name = name
self._workFromHome = workFromHome
self._leaveBalance = leaveBalance
@property
def employeeId(self):
return self._employeeId
@property
def name(self):
return self._name
@property
def workFromHome(self):
return self._workFromHome
@workFromHome.setter
def workFromHome(self, atHome):
self._workFromHome = atHome
@abstractmethod
def getLeaveEntitlement(self):
pass
#Other Methods
def adjustLeave(self, adjustment):
self._leaveBalance += adjustment
def __str__(self):
return f'ID {self._employeeId} Name: {self._name} Leave Balance: {self._leaveBalance} WFH: {self._workFromHome}'
def main():
e1 = Employee('101', 'Jeff', 20, 'Yes')
print(e1)
main()
TypeError Traceback (most recent call last) in 40 41 ---> 42 main()
in main() 36 def main(): 37 ---> 38 e1 = Employee('101', 'Jeff', 20, 'Yes') 39 print(e1) 40
TypeError: Can't instantiate abstract class Employee with abstract methods getLeaveEntitlement
If Working This is the Result: ID: 101 Name: Jeff Leave Balance: 20 WFH: No
Since Employee is an ABC, you cannot directly instantiate it. Only classes that 1) inherit from it, and 2) implement its abstract methods are allowed to be instantiated. There's nothing "wrong" with your code, this is a design constrain.
The following code adds the EmployeeChildClass
that inherits from Employee
and works as you'd expect:
from abc import ABC, abstractmethod
class Employee(ABC):
def __init__(self, employeeId, name, workFromHome, leaveBalance = 0):
self._employeeId = employeeId
self._name = name
self._workFromHome = workFromHome
self._leaveBalance = leaveBalance
@property
def employeeId(self):
return self._employeeId
@property
def name(self):
return self._name
@property
def workFromHome(self):
return self._workFromHome
@workFromHome.setter
def workFromHome(self, atHome):
self._workFromHome = atHome
@abstractmethod
def getLeaveEntitlement(self):
pass
#Other Methods
def adjustLeave(self, adjustment):
self._leaveBalance += adjustment
def __str__(self):
return f'ID {self._employeeId} Name: {self._name} Leave Balance: {self._leaveBalance} WFH: {self._workFromHome}'
# Dummy implementation
class EmployeeChildClass(Employee):
def getLeaveEntitlement(self):
return None
def main():
e1 = EmployeeChildClass('101', 'Jeff', 20, 'Yes')
print(e1)
main()
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.