python面向对象

 

封装

class Stu:
    def __init__(self, num: str, name: str, age: str)-> None:
        self._num = num
        self._name = name
        self._age = age

self代表类的实例, 而非类

类方法与普通函数的区别为类方法必须有一个额外首参数名称self

方法

class Person:
    def __init__(self, name: str)-> None:
        self._name = name

    # get方法
    @property
    def name(self)-> None:
        return self._name

    # set方法
    @name.setter
    def name(self, value: str)-> None:
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        self._name = value

操作

获值

class Person(object):
    def __init__(self, name: str, age: str)-> None:
        self.name = name
        self.age = age

p = Person('lili', 23)

# {'name': 'lili', 'age': 23}
print(p.__dict__)

赋值

class Person:
    # _obj为字典
    def __init__(self, _obj: dict)-> None:
        self.__dict__.update(_obj)

继承(Inheritance)

class 子类(父类)

单继承

# 父类
class People:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
    
    def speak(self) -> None:
        print("name = %s, age = %d" % (self.name, self.age))

不重写父类方法

class Student(People):
    def __init__(self, name: str, age: int, grade: str) -> None:
        # 调用父类实例化方法
        People.__init__(self, name, age)
        self.grade = grade


stu = Student(name="Wang", age=10. grade="No3")

stu.speak()

重写父类方法

class Student(People):
    def __init__(self, name: str, age: int, grade: str) -> None:
        # 调用父类实例化方法
        People.__init__(self, name, age)
        self.grade = grade

    # 重写父类方法
    def speak(self) -> None:
        print("name = %s, age = %d, grade = %s" %(self.name, self.age, self.grade))

stu = Student(name="Wang", age=10. grade="No3")
stu.speak()

多继承

class 子类(父类1, 父类2, 父类3...) 

继承顺序

写在前面的父类被优先继承

  • 父类中都存在show方法
class A:
    def show():
        print("A")

class B:
    def show():
        print("B")

class C:
    def show():
        print("C")


class X(A, B, C):
    pass

x = X()
x.show()
  • 只B父类中存在show方法
class A:
    pass

class B:
    def show():
        print("B")

class C:
    def show():
        print("C")


class X(A, B, C):
    pass

x = X()
x.show()