我正在尝试打印类的实例,但是我得到的结果似乎是正确的格式,但不是我正在寻找的输出。
我已经按照某人的建议使用了defstr(self(,但我仍然得到相同的结果
这是整个代码:
class Employee:
empCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __str__(self):
print (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)
这是我在命令行上得到的结果:
C:UsersDemiDesktopvirtuallearner>pr.py
z
2
Name : z , Salary: 2
Total Employee 1
m
5
Name : m , Salary: 5
Total Employee 2
[<__main__.Employee object at 0x0000022AFA278550>, <__main__.Employee object
at 0x0000022AFA278550>]
我正在尝试打印出在 for 循环中所做的更改的实例
您可以使用__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]
希望这有帮助!
这里有两点需要注意。
-
您没有调用实例的
str
方法。相反,您在容器上调用print
,这是alist_final
,这是一个列表。print(somelist)
将调用str方法somelist
,而不是list
中的元素 - 您没有返回字符串表示形式。取而代之的是,您用
print
来称呼它.
您需要从您实现的__str__
方法中return
表示形式,例如,
$ 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)']
添加__repr__
方法,该方法将在类的实例传递到 print 函数时运行。
def __repr__(self) -> str:
return f"employee<{name: {self.name}, salary: {self.salary}>"