创建动物对象,调用的时候提示缺失self参数
class Animal:
def run(self):
print("跑")
def eat(self):
print("吃")
wangcai = Animal
wangcai.eat()
wangcai.run()
C:\Users\infervision\PycharmProjects\pythonProject\venv\Scripts\python.exe E:/onedrive/python/python_/04day/xx_05动物继承.py
Traceback (most recent call last):
File "E:/onedrive/python/python_/04day/xx_05动物继承.py", line 11, in <module>
wangcai.eat()
TypeError: eat() missing 1 required positional argument: 'self'
Process finished with exit code 1
之前运行没问题,能够打印出跑和吃,之后再运行的时候就体术self参数缺失
类的实例化,不管有没有初始化参数,类名后面的括号是必要的
代码修改为
class Animal:
def run(self):
print("跑")
def eat(self):
print("吃")
wangcai = Animal()
wangcai.eat()
wangcai.run()
有帮助望采纳~
wangcai = Animal()
加了括号表示实例化,调用构造函数
不加括号,你的变量直接指向了类本身