1.
拷贝前赋值内存示意图
浅拷贝内存示意图,隐去部分不涉及的变量
深拷贝
2.
""" class Motor: def work(self): print("调用motor work") class Chassis: def work(self): print("调用chassis work") class Seat: def work(self): print("调用chassis work") class Shell: pass class Car(): def __init__(self,m,c,s,sh): self.m=m self.c=c self.s=s self.sh=sh def run(self): self.m.work() self.c.work() self.s.work() m1=Motor() c1=Chassis() s1=Seat() s2=Shell() car1=Car(m1,c1,s1,s2) car1.run()
3
class Computerfab: __obj=None __init_flag=True def __new__(cls, *args, **kwargs): if cls.__obj==None: cls.__obj=object.__new__(cls) return cls.__obj def __init__(self,brand): if Computerfab.__init_flag==True: self.brand=brand Computerfab.__init_flag=False def createpc(self): if self.brand=="Lenova": return Lenova() elif self.brand=="Asus": return Asus() elif self.brand=="Boat": return Boat() class Lenova: name="Lenova" def calculate(self): print("调用",self.name,self) class Asus(Lenova): name = "Asus" def calculate(self): super().calculate() class Boat(Asus): name = "Boat" def calculate(self): super().calculate() l=Computerfab("Lenova") a=Computerfab("Asus") b=Computerfab("Boat") print(l) l.createpc().calculate() print(a) a.createpc().calculate() print(b) b.createpc().calculate()
4.
class Empolyee: id=1000 def __init__(self,name,salary): Empolyee.id+=1 self.name=name self.__salary=salary @property def salary1(self): return self.__salary @salary1.setter def salary_setting(self,x): if 10000<x<50000: self.__salary=x else: print("错误,限定范围10000-50000") def __add__(self, other): if isinstance(other,Empolyee): return print(self.name,other.name,"工资总和",self.__salary+other.__salary) a=Empolyee("a",10000) b=Empolyee("b",20000) print(a,b) a+b a.salary_setting=9000 a.salary_setting=19000 print(a.salary1)