gpt4 book ai didi

python - 如何让 __str__ 或 __repr__ 返回当前类的名称?

转载 作者:行者123 更新时间:2023-12-05 00:43:36 24 4
gpt4 key购买 nike

我有这个代码:

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

现在,当我尝试运行时

emp1 = Employee("Ron", 1000, "male")
emp10 = Supervisor("Hermoine", 3000, "female", "General")
print(emp1, emp10)

我只在开头得到“员工姓名”。如何更改它以反射(reflect)“Hermoine”是 Supervisor 而不仅仅是 Employee,而无需重写 __str____repr__ 方法?

最佳答案

解决方案:

尝试将您的第一个类改为:

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"{self.__class__.__name__} name: {self.name}, and she earns {self.pay} Pound"
else:
return f"{self.__class__.__name__} name: {self.name}, and he earns {self.pay} Pound"

def __repr__(self):
if self.gender == "Female" or self.gender == "female":
return f"{self.__class__.__name__} name: {self.name}, and she earns {self.pay} Pound"
else:
return f"{self.__class__.__name__} name: {self.name}, and he earns {self.pay} Pound"

在所有字符串中尝试 self.__class__.__name__ 而不是 __class__.__name__

现在:

emp1 = Employee("Ron", 1000, "male")
emp10 = Supervisor("Hermoine", 3000, "female", "General")
print(emp1, emp10)

输出:

Employee name: Ron, and he earns 1000 Pound Supervisor name: Hermoine, and she earns 3000 Pound

说明:

self之所以返回实际的类名,是因为它会从当前的self实例中提取类名。没有 self 只会得到原始父类的类名,而不是它当前所在的实际类,这就是 self 如此重要的原因。

正如@MadPhysicist 提到的,它是“因为 __class__ 在类执行时是词法范围的”。

关于python - 如何让 __str__ 或 __repr__ 返回当前类的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69117926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com