没有self可以直接用类名调用函数,有self必须创建实例
class A:
def __init__(self):
self.mystr = 'hello world!'
def helloA(self):
print(self.mystr)
class B:
def helloB():
mystr = 'hello world!'
print(mystr)
if __name__ == '__main__':
A.helloA()
出错
Traceback (most recent call last):
File "E:/test/Python/class_self.py", line 23, in <module>
A.helloA()
TypeError: helloA() missing 1 required positional argument: 'self'
改为:
if __name__ == '__main__':
a=A()
a.helloA()
正确
if __name__ == '__main__':
B.helloB()
正确
网友评论