当前位置: 代码迷 >> 综合 >> [python] 类的 __init__(), __call__()方法使用
  详细解决方案

[python] 类的 __init__(), __call__()方法使用

热度:17   发布时间:2024-02-11 23:39:28.0

__init__():在创建实例的时候,把外部的传参绑到类的属性上。有了__init__()方法,在创建实例的时候就不能传入空的参数了,必须传入与__init__方法匹配的参数。

__call__()的方法是类在实例化以后,直接调用类的名字执行的方法。就像是把类当做是函数一样执行。

class Student(object):def __init__(self,name,score):self.name = nameself.score = scoredef __call__(self):print(self.name+'\'s score is ' +self.score)if __name__ == "__main__":student1 = Student('huo','98')student1()    #执行__call__()方法

>>>
=============== RESTART: C:\WORK\PythonScript\example\test.py ===============

huo's score is 98
>>>

  相关解决方案