我有课
class Phone:
def __init__(self, brand, name):
self.brand = brand
self.name = name
phone = Phone("apple", "iphone3")
所以我想将两个数据属性连接到结果
“苹果;iphone3”
我想避免
phoneData = phone.brand + ";" + phone.name
有什么想法吗?
提前致谢
没有办法避免它。但是你可以重写
__str__
和/或 __repr__
的 Phone
方法:
class Phone:
def __init__(self, brand, name):
self.brand = brand
self.name = name
def __str__(self):
return f'{self.brand};{self.name}'
phone = Phone("apple", "iphone3")
print(phone)
输出:
apple;iphone3