I have this code:
class Employee:
def __init__(self, name, pay, gender):
self.name = name
self.pay = pay
self.gender = gender
def add_raise(self):
self.pay = int(self.pay*1.10)
def __str__(self):
if self.gender == "Female" or self.gender == "female":
return f"{__class__.__name__} name: {self.name}, and she earns {self.pay} Pound"
else:
return f"{__class__.__name__} name: {self.name}, and he earns {self.pay} Pound"
def __repr__(self):
if self.gender == "Female" or self.gender == "female":
return f"{__class__.__name__} name: {self.name}, and she earns {self.pay} Pound"
else:
return f"{__class__.__name__} name: {self.name}, and he earns {self.pay} Pound"
class Supervisor(Employee):
def __init__(self, name, pay, gender, department):
super().__init__(name, pay, gender)
self.department = department
Now, when I try to run
emp1 = Employee("Ron", 1000, "male")
emp10 = Supervisor("Hermoine", 3000, "female", "General")
print(emp1, emp10)
I only get "Employee name" at the beginning. How do I change it so it reflects that "Hermoine" is a Supervisor
and not just an Employee
, without re-writing both the __str__
and __repr__
methods?
self.role = "Employee
orself.role = "Supervisor"
in the appropriate__init__
methods.role = "Employee"
directly in theclass
statement namespace.)self.__class__.__name__
approach suggested by @U12-Forward is a pretty common pattern for__repr__
methods. See, for example,collections.OrderedDict
,collections.Counter
,collections.namedtuple
andcollections.ChainMap
. github.com/python/cpython/blob/main/Lib/collections/__init__.pystr
. It's fine forrepr
, which is only intended as a debugging tool anyway. For__str__
, I'd rather use explicit data rather than a value inferred from code.__repr__
methods like this, and to leave__str__
undefined (meaning that calls to__str__
will fall back to the__repr__
method). I'm also not entirely sure why you don't consider the class name to be explicit data — it's very rare that you're dynamically setting or modifying a class name at runtime.