基础
class WashMachine():
def wash(self):
"""
self 当前对象-this
:return:
"""
print(f"正在洗衣服,宽度是{self.width},长度是{self.height}")
# 魔法方法 _xx_() 特殊功能的函数
def __init__(self, width=200, height=300):
self.width = width
self.height = height
# 打印对象的返回值
def __str__(self):
return "这是CG的类"
# 删除对象时调用
def __del__(self):
print("对象被删除")
washMachine = WashMachine(300, 400)
washMachine.wash()
washMachine.width = 100
washMachine.height = 200
print(washMachine.width, washMachine.height)
washMachine.wash()
print(washMachine.__str__(), washMachine)
del washMachine
# 调用函数后再删除,调用两次__del__()函数
# washMachine.__del__()
继承
class A(object):
def __init__(self):
self.num = 1
#方法,属性前加 __ 为私有属性
self.__money = 2000
def info_print(self):
print(f"A{self.num}")
class B(object):
def __init__(self):
self.num = 2
def info_print(self):
print(f"B{self.num}")
def b_info(self):
print("B")
class C(A):
def info_print(self):
print("C类重写A的info_print")
# 多继承,同名方法,默认集成第一个父类方法
class D(A, B):
def __init__(self):
self.num = 3
self.bb = 4
def info_print(self):
self.__init__()
print("num为" + str(self.num))
def info_print_A(self):
#按A父类来重新初始化继承的属性
A.__init__(self)
#调用A父类的方法
A.info_print(self)
def info_print_B(self):
B.__init__(self)
B.info_print(self)
def info_print_A_super(self):
#super()可以自动查找父类,调用顺序准寻_mro_类属性的顺序
#适合单继承使用
#第一个参数默认为当前对象的类名
super(D, self).__init__()
super().info_print()
result = C()
result.info_print()
result2 = D()
result2.info_print()
result2.b_info()
# 打印类的继承关系
# 元组
print(C.__mro__, D.__mro__)
# 序列
print(C.mro(), D.mro())
print("----------")
result2.bb = 5
result2.info_print()
print(result2.num, result2.bb)
result2.info_print_A()
print(result2.num, result2.bb)
result2.info_print_B()
print(result2.num, result2.bb)
result2.info_print_A_super()
classmethod,staticmethod
"""
类属性只能通过类对象修改,不能通过实例对象修改,如果通过实例对象修改,
表示创建了一个示例属性
"""
class Dog(object):
tooth = 10
wangcai = Dog()
xiaochei = Dog()
print(Dog.tooth)
print(wangcai.tooth)
print(xiaochei.tooth)
print("----------")
wangcai.tooth = 20
print(Dog.tooth)
print(wangcai.tooth)
print(xiaochei.tooth)
print("----------")
Dog.tooth = 30
print(Dog.tooth)
print(wangcai.tooth)
print(xiaochei.tooth)
print("----------")
# classmethod——类方法
"""
在已写好初始类的情况下,想给初始类再新添功能,不需要改初始类,只要在下一个类内部新写一个方法,方法用@classmethod装饰一下即可
"""
class ClassA(object):
arg1 = 0
arg2 = 1
def __init__(self, arg1=0, arg2=1):
self.arg1 = arg1
self.arg2 = arg2
def out_print(self):
print(f"arg1={self.arg1},arg2={self.arg2}")
# 对ClassA的补充
class ClassA_Add(ClassA):
@classmethod
def classAAdd(cls, arg1=0, arg2=1):
if arg1 < 0:
arg1 = 0
if arg2 < 1:
arg2 = 1
classA = cls(arg1, arg2)
return classA
classA = ClassA(5, 6)
classA.out_print()
classAAdd = ClassA_Add.classAAdd(-1, 0)
classAAdd.out_print()
# @staticmethod——静态方法
"""
不需要实例对象,不需要使用类对象,取消不需要的参数传递,减少不必要的内存占用和性能消耗
"""
class ClassB(object):
@staticmethod
def classBstaticMethod(*args):
print(f"静态方法,{args}")
ClassB.classBstaticMethod(1, 2, 3)