class Student:
group = 110 # 类变量
def __init__(self,name: str):
self.name = name
def get_name(self):
print(f"这个学生名字是{self.name}")
# 类方法
@classmethod
def get_age(cls,age: int):
print("类方法被调用")
print(f"年龄是{age},组别是{cls.group}")
# 静态方法 虽然写在类中,但不是属于这个类的方法,一个方法调用与这个类关系不大可以写成静态方法
@staticmethod
def get_sex(sex: str):
print("静态方法被调用")
print(f"性别是{sex}")
s1 = Student("小米")
s1.get_name()
s1.get_sex("男")
Student.get_sex("女")
s1.get_age(18)
Student.get_age(20)
python 类方法和静态方法
最新推荐文章于 2024-09-15 22:31:42 发布