1认识类-如何定义
- 类最基本作用:封装
- 类下面函数要加self
- 类下面函数变量需要用self引用
- 运行或者调用类要放在外部
class Student():
name = '' #定义变量
age = 0
def print_file():
print('name:'+str(age))
student = Student()#完成实例化的过程
student.print_file()#调用类下面方法
报错1
```ruby
D:\pythonProject1\venv\Scripts\python.exe C:\Users\Windows11\Desktop\面向对象\main.py
Traceback (most recent call last):
File "C:\Users\Windows11\Desktop\面向对象\main.py", line 7, in <module>
student.print_file()#调用类下面方法
TypeError: Student.print_file() takes 0 positional arguments but 1 was given
Process finished with exit code 1
需要在类的函数里面加上self固定格式
class Student():
name = '' #定义变量
age = 0
def print_file(self):
print('name:'+name)
print('age:'+str(age))
student = Student()#完成实例化的过程
student.print_file()#调用类下面方法
报错2
D:\pythonProject1\venv\Scripts\python.exe C:\Users\Windows11\Desktop\面向对象\main.py
Traceback (most recent call last):
File "C:\Users\Windows11\Desktop\面向对象\main.py", line 7, in <module>
student.print_file()#调用类下面方法
File "C:\Users\Windows11\Desktop\面向对象\main.py", line 5, in print_file
print('name:'+str(age))
NameError: name 'age' is not defined
Process finished with exit code 1
需要加上self关键字
class Student():
name = '' #定义变量
age = 0
def print_file(self):
print('name:'+self.name)
print('age:'+str(self.age))
student = Student()#完成实例化的过程
student.print_file()#调用类下面方法