项目场景:
class Student:
def __init__(self,name,age,tel):
self.name = name
self.age = age
self.tel = tel
print("jj")
stu = Student("周杰轮",31,"45654")
print(stu)
问题描述
print(stu)
结果为
jj
<__main__.Student object at 0x0000020E0CC58FA0>
原因分析:
调用的是对象的地址,而不是属性
解决方案:
方法一
print(stu.name)
print(stu.age)
print(stu.tel)
周杰轮
31
45654
方法二
通过_str_方法,控制类转换为字符串的行为
方法名:__str__
返回值:字符串
内容:自行定义
def __str__(self):
return f"Student类对象,name={self.name},age={self.age},tel={self.tel}"
Student类对象,name=周杰轮,age=31,tel=45654
文章介绍了Python中创建类`Student`的例子,指出在打印对象时默认显示的是内存地址而非属性值。提供了两种解决方案:一是直接访问对象属性如`stu.name`;二是重写`__str__`方法,自定义对象转为字符串的表现形式,使打印结果更易读。
9万+





