VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • python基础学习(十二)

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结果:


相关教程