1、面向对象的三大特征:封装、继承、多态
2、封装
class Car:
def __init__(self,brand):
self.brand = brand
def start(self):
print("汽车已启动...")
car = Car("宝马X5")
car.start()
print(car.brand)
输出结果:
汽车已启动…
宝马X5
如果属性不希望在类对象外部被访问,前边使用两个"_"
#如果属性不希望在类对象外部被访问,前边使用两个"_"
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(stu.name)
#print(stu.__age) #报错,在类的外部无法使用age
输出结果:
张三 20
张三
但是如果真的想要在类的外部使用age,可以通过_Student__age访问
#但是如果真的想要在类的外部使用age,可以通过_Student__age访问
print(stu._Student__age) #用不用全靠程序员的自觉性
输出结果:
20
3、继承
3.1
如果一个类没有继承任何类,则默认继承object
下面的程序,Student和Teacher都继承Person
继承的类中,注意init的写法
#如果一个类没有继承任何类,则默认继承object
class Person(object): #Person继承object类,(object)可省略不写
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person): #Student继承Person
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
def info(self): #子类中方法重写
super().info()
print("学号",self.stu_no) #记得要写self.
class Teacher(Person): #Teacher继承Person
def __init__(self,name,age,yearofteacher):
super().__init__(name,age)
self.yearofteacher = yearofteacher
def info(self):
super().info() #子类重写后的方法中可以通过super().xxx()调用父类中被重写的方法
print("教龄",self.yearofteacher) #记得要写self.
stu = Student('张三',24,'2016')
teacher = Teacher('李四',35,10)
stu.info()
teacher.info()
输出结果:
张三 24
学号 2016
李四 35
教龄 10
3.2 可以多继承,如
class A(object):
pass
class B(object):
pass
class C(A,B): #C继承了A和B
pass
3.3 方法重写
如果子类对继承自父类的某个属性或方法不满意,可以在子类中对其(方法体)进行重新编写
子类重写后的方法中可以通过super().xxx()调用父类中被重写的方法
如下面两个子类的info(self)方法
class Student(Person): #Student继承Person
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
def info(self): #子类中方法重写
super().info() #调用父类中被重写的方法
print("学号",self.stu_no) #记得要写self.
class Teacher(Person): #Teacher继承Person
def __init__(self,name,age,yearofteacher):
super().__init__(name,age)
self.yearofteacher = yearofteacher
def info(self): #子类中方法重写
super().info() #调用父类中被重写的方法
print("教龄",self.yearofteacher) #记得要写self.
3.4 object类
如果一个类没有继承其他类,都默认继承object类,因此所有的类都会有object类的属性和方法
内置函数dir()可以查看指定对象所有属性
class Student:
pass
stu = Student()
print(dir(stu)) #输出从object类中继承过来的所有属性
输出结果:
[‘class’, ‘delattr’, ‘dict’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘module’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘weakref’]
(每个属性前后都有下划线__,这里显示不出来)
object中有一个_str_()方法,用于返回一个对于“对象的描述”
#object中有一个_str_()方法,用于返回一个对于“对象的描述”
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return "我叫{0},今年{1}岁".format(self.name,self.age)
stu = Student("林心淇",20)
print(stu) #默认会调用__str__这样的方法
输出结果:
我叫林心淇,今年20岁
4、多态
class Animal:
def eat(self):
print("动物会吃东西")
class Dog(Animal):
def eat(self):
print("狗吃骨头...")
class Cat(Animal):
def eat(self):
print("猫吃鱼...")
class Person:
def eat(self):
print("人吃五谷杂粮")
def fun(obj):
obj().eat()
fun(Animal)
fun(Dog)
fun(Cat)
fun(Person)
输出结果:
动物会吃东西
狗吃骨头…
猫吃鱼…
人吃五谷杂粮
5、特殊属性 前后有加__的
class A:
pass
class B:
pass
class C(A,B):
def __init__(self,name,age):
self.name = name
self.age = age
class D(A):
pass
x = C('Jack',20)
print(x.__dict__) #输出实例对象的属性字典
print(C.__dict__)
输出结果:
{‘name’: ‘Jack’, ‘age’: 20}
{‘module’: ‘main’, ‘init’: <function C.init at 0x0000016D674595E8>, ‘doc’: None}
print(x.__class__) #输出对象所属的类 <class '__main__.C'>
print(C.__bases__) #C类的父类类型的元素
print(C.__base__) #类的基类(谁写在前面,就输出谁)
print(C.__mro__) #输出类的层次结构
print(A.__subclasses__()) #查看A的子类
输出结果:
<class ‘main.C’>
(<class ‘main.A’>, <class ‘main.B’>)
<class ‘main.A’>
(<class ‘main.C’>, <class ‘main.A’>, <class ‘main.B’>, <class ‘object’>)
[<class ‘main.C’>, <class ‘main.D’>]
(以上结果的下划线__无法显示)
6、特殊方法 前后有加__的方法
class Student:
def __init__(self,name):
self.name = name
def __add__(self,other):
return self.name+other.name #想要让两个对象具有相加的功能,就要写__add__这个特殊的方法
def __len__(self):
return len(self.name)
stu1 = Student("张三")
stu2 = Student("李四")
stu3 = Student("Jack")
s = stu1+stu2 #实现了两个对象的加法运算(因为在Student类中,编写__add__()这个特殊的方法
print(s)
s = stu1.__add__(stu2) #效果同上
print(s)
输出结果:
张三李四
张三李四
lst = [11,22,33,44]
print(len(lst))
print(lst.__len__())
print(len(stu1)) #当没有定义len时,这个会报错,在类中定义该方法
print(len(stu3))
输出结果:
4
4
2
4
7、
class CPU:
pass
class Disk:
pass
class Computer:
def __init__(self,cpu,disk):
self.cpu = cpu
self.disk = disk
7.1 变量的赋值
cpu1 = CPU()
cpu2 = cpu1
print(cpu1,id(cpu1))
print(cpu2,id(cpu2))
输出结果:
<main.CPU object at 0x000001BA0E0B73C8> 1898611176392
<main.CPU object at 0x000001BA0E0B73C8> 1898611176392
7.2 类的浅拷贝
disk = Disk()
computer = Computer(cpu1,disk)
#开始浅拷贝 只拷贝实例对象computer,里面的子对象cpu和disk不拷贝(因此computer和computer2的地址不同,cpu和disk的地址会是一样的)
import copy
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
输出结果:
<main.Computer object at 0x000001BA0E0B74C8> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>
<main.Computer object at 0x000001BA0E0B7588> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>
7.3 类的深拷贝 不仅拷贝实例对象,里面的子对象cpu和disk也拷贝
computer3 = copy.deepcopy(computer)
print(computer,computer.cpu,computer.disk)
print(computer3,computer3.cpu,computer3.disk)
输出结果:
<main.Computer object at 0x000001BA0E0B74C8> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>
<main.Computer object at 0x000001BA0E0B7608> <main.CPU object at 0x000001BA0E0B7648> <main.Disk object at 0x000001BA0E0B7688>
从结果可知,三种变量的地址分别都不同