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結果:spa
更改__namecode
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結果:blog
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結果:get