目录
封装
将对象的属性和实现细节隐藏起来,只对外提供必要的接口或方法。
继承
让子类具有父类的特性,提高了代码的重用性。
继承的语法格式如下:
class 子类类名(父类 1[,父类 2,...]):
类体
子类可以重新定义父类中的方法,这样就会覆盖父类的方法,也称为“重写。
class Person:
def __init__(self,name,age):
self.name=name
self.__age=age
def say_age(self):
print('年龄,年龄,我也不知道')
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)#必须显示去调用
self.score=score
print(Student.mro())
a=Student('xg',18,60)
a.say_age()
print(a.name)
# print(a.age)
print(dir(a))
print(a._Person__age)
通过类的方法 mro()或者类的属性__mro__可以输出这个类的继承层次结构。
class A:pass
class B(A):pass
class C(B):pass
print(C.mro())
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
重写方法
class Person:
def __init__(self,name,age):
self.name=name
self.__age=age
def say_age(self):
print('年龄,年龄,我也不知道')
def say_introduce(self):
print("我的名字是{0}".format(self.name))
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)#必须显示去调用
self.score=score
def say_introduce(self):
#重写父类方法
print('报告老师,我的名字是:{0}'.format(self.name))
s=Student('李健',18,80)
s.say_age()
s.say_introduce()
object 有一个__str__()方法,用于返回一个对于“对象的描述”,对应于内置函数 str()
经常用于 print()方法,帮助我们查看对象的信息。__str__()可以重写
def __str__(self):
'''将对象转化成一个字符串,一般用于 print 方法'''
return "名字是:{0},年龄是{1}".format(self.name,self.__age)
p = Person("高",18)
print(p)
多态
多态是指同一个方法调用由于对象不同会产生不同的行为。
#多态
class Man:
def eat(self):
print("饿了,吃饭啦!")
class Chinese(Man):
def eat(self):
print("中国人用筷子吃饭")
class English(Man):
def eat(self):
print("英国人用叉子吃饭")
class Indian(Man):
print("印度人用右手吃饭")
def manEat(m):
if isinstance(m,Man):#表示m是Man的子类么
m.eat()
else:
print("不能吃饭")
manEat(Chinese())
manEat(English())
特殊方法和运算符重载
a = 20
b = 30
c = a+b
d = a.__add__(b)
print("c=",c)
print("d=",d)
#测试运算符的重载
class Person:
def __init__(self,name):
self.name=name
def __add__(self,other):
if isinstance(other,Person):
return "{0}--{1}".format(self.name,other.name)
else:
return "不是同类对象,不能添加"
def __mul__(self, other):
if isinstance(other,int):
return self.name*other
else:
return "不是同类对象,不能添加"
p1=Person("好滴")
p2=Person("好的")
x=p1 + p2
print(x*3)
对象的浅拷贝和深拷贝
Python 拷贝一般都是浅拷贝。拷贝时,对象包含的子对象内容不拷贝。因此,源对象和拷贝对象会引用同一个子对象。
·深拷贝
使用 copy 模块的 deepcopy 函数,递归拷贝对象中包含的子对象。源对象和拷贝对象所有的子对象也不同。
设计模式_工厂模式实现
工厂模式
#测试工厂模式
class Carfactory:
def create_car(self,brand):
if brand=="奔驰":
return Benz()
elif brand=="宝马":
return BMW()
elif brand=="比亚迪":
return BYD()
else:
return "未知品牌,无法创建"
class Benz:
pass
class BMW:
pass
class BYD:
pass
factory=Carfactory()
c1=factory.create_car("奔驰")
c2=factory.create_car("比亚迪")
print(c1)
print(c2)