24. The class function
# Class function # class methods class Student: DEF the __init__ (Self, name, Age, Sex): # __name__ __age __sex internal attributes This ensures that the external can not be freely modified Self. __Name__ = name Self. __Age = Age Self. __Sex = Sex DEF print_info (Self): Print (F ' {name} Self .__ - .__ Self Age} {-} {Sex Self .__ ' ) # student example S DEF print_info (S): Print (F ' {s.name} - {S } .age - s.sex {} ') jack = Student("jack.a", 13, "男") # print_info(jack) print("---------------------------------------") jack.name = "ab" jack.print_info()
run results:
Change __name
class Student: DEF the __init__ (Self, name, Age, Sex): # __name__ __age __sex internal attributes This ensures that the external can not be freely modified Self. __name__ = name Self. __age = Age Self. __sex = Sex DEF print_info (Self): Print (F ' {name} Self .__ - .__ Self Age} {-} {Sex Self .__ ' ) DEF get_name (Self): return . Self __name__ DEF set_name (Self, name): . Self __name__ = name # 学生实例 s def print_info(s): print(f'{s.name}-{s.age}-{s.sex}') jack = Student("jack.a", 13, "男") print(jack.get_name()) print("---------------------------------------") jack.name = "ab" jack.set_name("ba") jack.print_info()
run results: