Python 特殊方法

时间:2023-03-10 07:12:12
Python 特殊方法

1 _int_

定义在类中,创建类的实例的时候回先调用此方法,用于对该类的一些初始化(例如变量初始化)

2 _str_

    def _str_(self):
return "this is a string'

  定义在类中,用print调用类的时候,会调用到此方法

class strtest:
def __str__(self):
return "str: this is only test" if __name__ == "__main__":
st=strtest()
print st

 执行结果为:

$./str.py

str: this is only test