3 回答
TA贡献1995条经验 获得超2个赞
您可以使用 __repr__ 方法,而不是使用__str__方法。使用此方法,您无需将实例显式转换为字符串。找到代码:
class Employee:
empCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __repr__(self):
return self.name
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ",self.salary)
global emp1
global emp2
global n
global s
emp1 = ''
emp2 = ''
alist = [emp1,emp2]
alist_final =[]
for y in alist:
y = Employee('n',2)
alist_final.append(y)
y.displayEmployee()
print("Total Employee %d" % Employee.empCount)
print(alist_final)
输出如下:
Name : n , Salary: 2
Total Employee 1
Name : n , Salary: 2
Total Employee 2
[n, n]
希望这可以帮助!
TA贡献1860条经验 获得超9个赞
这里有两点需要注意。
您没有调用
str
实例的方法。相反,您正在调用print
容器,即alist_final
,它是一个列表。print(somelist)
将调用 str 方法somelist
,而不是list
您没有返回字符串表示形式。取而代之的是,您使用
print
.
您需要return
从__str__
您实现的方法中进行表示,例如,
$ cat emp.py
class Employee:
empCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __str__(self):
return '{}(name={}, salary={})'.format(
self.__class__.__name__,
self.name,
self.salary)
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ",self.salary)
alist_final =[]
for _ in range(2):
y = Employee('n',2)
alist_final.append(y)
y.displayEmployee()
print("Total Employee %d" % Employee.empCount)
print([str(x) for x in alist_final])
输出:
$ python emp.py
('Name : ', 'n', ', Salary: ', 2)
Total Employee 1
('Name : ', 'n', ', Salary: ', 2)
Total Employee 2
['Employee(name=n, salary=2)', 'Employee(name=n, salary=2)']
TA贡献1817条经验 获得超6个赞
添加__repr__
将在您的类的实例传递到打印函数时运行的方法。
def __repr__(self) -> str: return f"employee<{name: {self.name}, salary: {self.salary}>"
添加回答
举报