目录
定义格式
class ClassName:
<statement-1>
.
.
.
<statement-N>
类对象
- 操作方式:属性引用和实例化
# -*- coding: utf-8 -*-
# @Time : 2021/4/11
# @Author : 大海
class MyClass(object):
i = 12345
def test(self):
return f'hello world {self.i}'
if __name__ == '__main__':
# 属性引用所使用的标准语法: obj.name
print(MyClass.i)
print(MyClass.test)
# 实例化
x = MyClass()
print(x.i)
print(x.test)
继承
- 单继承
# -*- coding: utf-8 -*-
# @Time : 2021/4/11
# @Author : 大海
# 父类
class A(object):
def __init__(self):
self.num = 10
def print_num(self):
print(self.num + 10)
# 子类
class B(A):
pass
if __name__ == '__main__':
b = B()
print(b.num)
b.print_num()
- 多继承
# -*- coding: utf-8 -*-
# @Time : 2021/4/11
# @Author : 大海
class Master(object):
def __init__(self):
self.kongfu = "古法煎饼果子配方" # 实例变量,属性
def make_cake(self): # 实例方法,方法
print("[古法] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
def dayandai(self):
print("师傅的大烟袋..")
class School(object):
def __init__(self):
self.kongfu = "现代煎饼果子配方"
def make_cake(self):
print("[现代] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
def xiaoyandai(self):
print("学校的小烟袋..")
class Prentice(Master, School): # 多继承,继承了多个父类(Master在前)
pass
if __name__ == '__main__':
damao = Prentice()
print(damao.kongfu) # 执行Master的属性
damao.make_cake() # 执行Master的实例方法
# 子类的魔法属性__mro__决定了属性和方法的查找顺序
print(Prentice.__mro__)
damao.dayandai() # 不重名不受影响
damao.xiaoyandai()
调用父类
# -*- coding: utf-8 -*-
# @Time : 2021/4/11
# @Author : 大海
class Master(object):
def __init__(self):
self.kongfu = "古法煎饼果子配方" # 实例变量,属性
def make_cake(self): # 实例方法,方法
print("[古法] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
# 父类是 Master类
class School(Master):
def __init__(self):
self.kongfu = "学校煎饼果子配方"
def make_cake(self):
print("[学校] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
super().__init__() # 执行父类的构造方法
super().make_cake() # 执行父类的实例方法
print("[学校] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
# 父类是 School 和 Master
class Student(School, Master): # 多继承,继承了多个父类
def __init__(self):
super().__init__()
# 重写父类属性
self.kongfu = "学生煎饼果子配方"
def make_cake(self):
self.__init__() # 执行本类的__init__方法,做属性初始化 self.kongfu = "猫氏...."
print("[学生] 按照 <%s> 制作了一份煎饼果子..." % self.kongfu)
def make_all_cake(self):
super().__init__() # 执行父类的 __init__方法
super().make_cake() # 执行父类的 实例方法
self.make_cake() # 执行本类的实例方法
if __name__ == '__main__':
student = Student()
student.make_cake()
student.make_all_cake()
单例模式
# -*- coding: utf-8 -*-
# @Time : 2021/4/11
# @Author : 大海
# 实例化一个单例
class Singleton(object):
__instance = None
__is_first = True
def __new__(cls, age, name):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, age, name):
if self.__is_first:
self.age = age
self.name = name
Singleton.__is_first = False
if __name__ == '__main__':
a = Singleton(18, "我是测试小白")
print(id(a))
print(a.age)
b = Singleton(28, "我是测试小白")
print(id(a))
print(id(b))
print(a.age)
print(b.age)
a.age = 19
print(b.age)