使用类时中的代码出现问题


class Customer:
"""The people who are going to be accessing this program"""

def __init__(self, first, last, gender, age):
self.first = first 
self.last = last
self.gender = gender
self.age = age
def buying_something(self):
"""The customer is now buying something"""
print(f"{self} is now buying something")
def browsing(self):
"""The customer is now browsing something"""
print(f"{self} is now browsing something")
customer_1 = Customer('John', 'Doe', 'Male', 20)
print(f"This customers name is {customer_1.first}")
print(f"This customers age is {customer_1.age}")
customer_1.buying_something()

这是我所做的一些代码,试图实现我迄今为止在类上学到的东西。我的问题是我输入的最后一行代码。正如你在下面看到的,这是我得到的输出。

This customers name is John
This customers age is 20
<__main__.Customer object at 0x7f09f6c494c0> is now buying something

类中需要有__str____repr__方法

添加此代码

def __str__(self):
return f'{self.first}_{self.last}_{self.age}_{self.gender}'

它会打印一些东西John_Doe_20_Male is now buying something

最新更新