[英]How to use print to display class instances in python
我正在嘗試打印 class 的實例,但我得到的結果似乎格式正確,但不是我要查找的 output。
我已經按照某人的建議使用了 def str (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:\Users\Demi\Desktop\virtuallearner>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 循環中所做更改的實例
這里有兩點需要注意。
您沒有調用實例的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])
Output:
$ 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__方法,而不是使用__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)
Output 就像:
Name : n , Salary: 2
Total Employee 1
Name : n , Salary: 2
Total Employee 2
[n, n]
希望這可以幫助!
添加__repr__
方法,該方法將在您的 class 的實例傳遞到打印 function 時運行。
def __repr__(self) -> str:
return f"employee<{name: {self.name}, salary: {self.salary}>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.