0.python dataclass 官方文档:
dataclasses — Data Classes — Python 3.10.4 documentation
1@dataclass是什么:
请看0~
2 @dataclass使用
2.1
首先引入dataclass.
使用此装饰器,新建student类,后续直接使用即可。
from dataclasses import dataclass
@dataclass
class Student:
grade: int = 60
def test_demo():
print(Student)
print(Student.grade)
输出:
60
2.2 dataclass的一些简单使用
from dataclasses import dataclass
@dataclass
class Student:
# 定义学生类
grade: int = 59
pass_grade: int = 60
def pass_or_not(self):
# 简单的比较
if self.grade > self.pass_grade:
return True
else:
return False
def test_demo():
xiaoming = Student(grade=60, pass_grade=59)
# 新建学生小明,赋予小明成绩
print(xiaoming.pass_or_not())
xiaohong = Student()
# 新建学生小红,使用默认成绩
print(xiaohong.pass_or_not())
2.3
@dataclass
class Student:
# 定义学生类
grade: int = 59
pass_grade: int = 60
def pass_or_not(self):
# 简单的比较
if self.grade > self.pass_grade:
return True
else:
return False
@dataclass
class Boy:
# 直接使用student类型数据
student: Student = Student
name: str = "boy"
def test_demo():
boy = Boy()
print(boy.student.grade)
print(asdict(boy))
new_boy = Boy(asdict(Student()))
print(asdict(new_boy))
输出
59
{'student': , 'name': 'boy'}
{'student': {'grade': 59, 'pass_grade': 60}, 'name': 'boy'}