在Python中将类方法作为属性引用,但没有返回错误?

2024-09-29 21:49:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,我应该引用类方法printID作为student.printID(),但是我错误地引用了student.printID,我认为它应该返回一个名称错误/异常,但是代码运行没有任何问题,有什么想法为什么

class Student:
        def __init__(self, id):
                self.id = id
        def printID(self):
                print self.id

student = Student(100)

student.printID

提前谢谢, 林


Tags: 方法代码self名称idinitdef错误
1条回答
网友
1楼 · 发布于 2024-09-29 21:49:24

Python中的方法和属性之间没有真正的区别。方法是属性student.printID是对method对象的引用。当你给它加上括号时,你称它为对象。换句话说,student.printID()和:

x = student.printID
x()

因此,键入student.printID而不使用括号不是错误的。它只是给你一个方法的参考。您可能希望将该引用用于其他用途(在您的特定情况下,您没有对它做任何操作,但Python不知道这一点。)

相关问题 更多 >

    热门问题