以下代码运行出错,什么原因呢?
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
AttributeError: 'Test' object has no attribute '_class_'
以下代码运行出错,什么原因呢?
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
AttributeError: 'Test' object has no attribute '_class_'
以下回答参考 皆我百晓生、券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。
在Python中,__class__ 是一个私有属性,只有类本身才能访问。因此,在你的例子中,当你尝试访问 t.prt() 时,它会抛出一个错误。
要解决这个问题,你需要将 self.__class__ 替换为 type(t),这将在对象类型上获取当前类的引用:
class Test:
def prt(self):
print(self)
print(type(self))
t = Test()
t.prt() # 这行将正常执行
在这个例子中,我们使用了 type(self) 来获取当前类的类型,并打印出来。这样就解决了 AttributeError: 'Test' object has no attribute '_class_' 的问题。