封装
class Student:
def __init__(self,name,age):
self.name=name
self.__age=age
def show(self):
print(self.name,self.__age)
stu=Student('张三',20)
stu.show()
print(dir(stu))
print(stu._Student__age)
继承
class Person():
def __init__(self,name,age):
self.name=name
self.age=age
def info(self):
print(self.name,self.age)
class Stu(Person):
def __init__(self,name,age,sno):
super().__init__(name,age)
self.sno=sno
class Teacher(Person):
def __init__(self,name,age,ty):
super().__init__(name,age)
self.ty=ty
stu1=Stu('张三',20,'1001')
t1=Teacher('李四',50,'20')
stu1.info()
t1.info()
方法重写
class Stu(Person):
def __init__(self,name,age,sno):
super().__init__(name,age)
self.sno=sno
def info(self):
super().info()
print(self.sno)
class Teacher(Person):
def __init__(self,name,age,ty):
super().__init__(name,age)
self.ty=ty
def info(self):
super().info()
print(self.ty)
#object类
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return f"名字:{self.name}\t 年龄:{self.age}"
stu=Student('zsy', 19)
print(stu)
多态
class Animal:
def __init__(self,species,age):
self.species=species
self.age=age
def eat(self):
print(f"动物在吃饭")
class Dog(Animal):
def __init__(self,species,age):
super().__init__(species,age)
def eat(self):
print(f"{self.species}在吃饭,已经{self.age}岁了。")
class Tiger(Animal):
def __init__(self,species,age):
super().__init__(species,age)
def eat(self):
print(f"{self.species}在吃饭,已经{self.age}岁了。")
def fun(a1):
a1.eat()
an=Animal('动物',0)
an.eat()
dog1=Dog('哈士奇', 5)
fun(dog1)
t1=Tiger('老虎',7)
fun(t1)
特殊方法和特殊属性
class A:
pass
class B:
pass
class C(A,B):
def __init__(self,name,age):
self.name=name
self.age=age
x=C('zsy',20)
print(x.__dict__)
print(x.__class__)
print(C.__bases__)
print(C.__mro__)
重定义类内方法
a=20
b=100
d=a.__add__(b)
class S:
def __init__(self,name):
self.name=name
def __add__(self,other):
return self.name+other.name
def __len__(self):
return len(self.name)
s1=S('张三')
s2=S('李四')
s_=s1+s2
s=s1.__add__(s2)
print(s_,s)
print('**************************************')
lst=[1,23,4,5,6]
print(len(lst))
print(lst.__len__())
print(len(s1))
浅拷贝和深拷贝
class Cpu:
pass
class Disk:
pass
class Computer:
def __init__(self,cpu,disk):
self.cpu=cpu
self.disk=disk
cpu1=Cpu()
disk=Disk()
comp1=Computer(cpu1, disk)
import copy
comp2=copy.copy(comp1)
print(comp1,comp1.cpu,comp1.disk)
print(comp2,comp2.cpu,comp2.disk)
print('----------------------------------------')
comp3=copy.copy(comp1)
print(comp1,comp1.cpu,comp1.disk)
print(comp3,comp3.cpu,comp3.disk)
|