Python 中的类和继承

145 阅读1分钟

前置知识:

if-else

score = 59
if score > 60:
    print("及格")
else:
    print("不及格")

list

name = ['aa', 'bb', 'cc']
for item in name:
    print(item)

image.png tuple

name = ('aa', 'bb', 'cc')
for item in name:
    print(item)

name[2] = 'zz'

内容不可变

image.png dict 字典

name = {'aa': 34, 'bb': 64, 'cc': 74}
print(name['bb'])

set 无序不重复 image.png set_ = set ([]) 函数

def test_test():
    print(1 == 1)

test_test() # true

1.定义类

定义类以及类的共有属性、私有属性、实例方法、类方法

class Person(object):
    __location = 'huBei'

    def __init__(self, name, sex, age):
        # 私有属性
        self.__name = name
        self.sex = sex
        self.age = age
        
    # 访问私有属性
    def get_name(self):
        return self.__name

    # 类方法
    @classmethod
    def set_location(cls, location):
        cls.__location = location

    @classmethod
    def get_location(cls):
        return cls.__location

2.类的继承

class Student(Person):
    # 执行父类的初始化方法
    def __init__(self, name, sex, age, score):
        super(Student, self).__init__(name, sex, age)
        self.score = score

student = Student('yaoYao', 1, 17, 88)
# isinstance 判断原型
print(student.age, student.score, isinstance(student, Person))  # 17 88 True