面向对象的三大特征:
封装:提高程序的安全性 1。将数据(属性)和行为(方法)包装到类对象中,在方法内部对属性进行操作,在类对象对外部调用方法。 这样无需关心方法内部对细节,从而隔离了复杂度 2。在python中没有专门对修饰符用于属性对私有,如果该属性不希望在类对象外部被访问,前面使用两个"__" 继承:提高代码的复用性 多态:提高程序的可扩张性和可维护性
object类 object类是所有类的父类,因此所有类都有object类的属性和方法 内置函数dir()可以查看指定对象所有属性 object有一个__str__()方法,用于返回一个对于"对象的描述",对应于内置函数str()经常用于print()方法, 帮助我们查看对象的信息,所以我们经常会对__str__()进行重写 特殊属性: __dict__() 获得类对象或实例对象所绑定的所有属性和方法的字典 特殊方法: __len__() 通过重写__len__()方法。让内置函数len()的参数可以是自定义类型 __add__() 通过重写可以使用自定义对象具有'+'功能 __new__() 创建对象 __init__() 对创建对对象进行初始化
访问私有属性:
class Car:
def __init__(self, brand='car', password=''):
self.brand = brand
# 私有属性只能在内部使用,外部不能直接用
# 但是可以通过 _Car__password 使用, 不建议这样用
self.__password = password
def run(self):
print(self.brand + ' 已启动')
def __str__(self):
return self.brand
class BMW(Car):
def run(self):
print('bmw: run')
class Ben(Car):
def run(self):
print('ben: run')
bmw1 = Car('bmw', 66666)
bmw1.run()
print(bmw1._Car__password)
print(dir(bmw1))
print(bmw1)
print('-----')
# 多态
def run(obj):
return obj.run()
run(BMW())
print('--特殊属性--')
print(bmw1.__dict__) # 实例对象的属性字典
print(Car.__dict__)
print(bmw1.__class__) # 实例对象所属的类
print(Car.__bases__) # Car类的父类类型的元素
print(Car.__module__) # 类的层次结构
print(Car.__subclasses__()) # 子类的列表