python基础学习(十二)
程序员文章站
2022-05-23 11:06:05
24.类函数 # 类函数 # 类方法 class Student: def __init__(self, name, age, sex): # __name __age __sex 内部属性 这样保证了外部不能随意修改 self.__name = name self.__age = age self ......
24.类函数
# 类函数 # 类方法 class student: def __init__(self, name, age, sex): # __name __age __sex 内部属性 这样保证了外部不能随意修改 self.__name = name self.__age = age self.__sex = sex def print_info(self): print(f'{self.__name}-{self.__age}-{self.__sex}') # 学生实例 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结果:
更改__name
class student: def __init__(self, name, age, sex): # __name __age __sex 内部属性 这样保证了外部不能随意修改 self.__name = name self.__age = age self.__sex = sex def print_info(self): print(f'{self.__name}-{self.__age}-{self.__sex}') 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结果:
25.继承
# 继承 class person: def __init__(self, name, age, sex): # __name __age __sex 内部属性 这样保证了外部不能随意修改 self.__name = name self.__age = age self.__sex = sex # 函数 父类 def who_am_i(self): print(f'i am a person,{self.__name}-{self.__age}-{self.__sex}') def get_name(self): return self.__name def set_name(self, name): self.__name = name def get_age(self): return self.__age def set_age(self, age): self.__age = age def get_sex(self): return self.__sex def set_sex(self, sex): self.__sex = sex sk = person("song ke", 22, "男") sk.who_am_i() print("------------1-------------------") sk.set_name("ks") sk.set_age(23) sk.who_am_i() class student(person): # 子类 父类有定义,子类也定义 优先执行子类中方法 def who_am_i(self): print(f'i am a student,{self.get_name()}, {self.get_age()}, {self.get_sex()}') def learn(self): print("i am learning") class teacher(person): def who_am_i(self): print(f'i am a teacher,{self.get_name()}, {self.get_age()}, {self.get_sex()}') def teach(self): print("i am teaching") print("-------------2---------------") zs = student("yang", 24, "女") zs.who_am_i() zs.learn() print("-------------3----------------") zz = teacher("zha", 35, "男") zz.who_am_i() zz.teach()
run结果:
上一篇: nodejs随手记
下一篇: 吃魔芋减肥吗,真相在这里