Python面向对象--高级(二)

时间:2022-02-18 22:21:25

## 使用__slots__限制类的属性
  - 之前说到,可以通过在类外部实例或者类名任意定义实例属性或者类属性或者方法

 class Person(object):
pass Person.name = "Stanley" # 在外部添加类属性
print(Person.name) # 输出:Stanley per1 = Person()
per1.age = 22 # 在外部添加实例属性
print(per1.age) # 输出:22 per2 = Person()
# print(per2.age) # 实例属性只由定义该属性的实例所有,其他的实例无法访问 def outer_init(self, name):
self.name = name Person.__init__ = outer_init # 在外部修改类方法
per3 = Person("Lily")
print(per3.name) # 输出:Lily, 说明类方法修改成功

  - 若想要限制实例的属性,可以使用__slots__

 class Person(object):
__slots__ = ("name", "age") # 限制实例属性
count = 1 Person.nationality = "China" # 仍然可以定义类属性
print(Person.nationality) # 输出:China per1 = Person()
per1.name = "Lily"
per1.age = 17 per1.nationality = "China"
# 类属性为只读属性,无法通过实例修改,只能通过类名修改
# AttributeError: 'Person' object attribute 'nationality' is read-only per1.gender = "female"
# 无法通过实例定义新实例属性
# AttributeError: 'Person' object has no attribute 'gender' per1.count = 100
# AttributeError: 'Person' object attribute 'count' is read-only

## 多重继承
  - Python是允许多重继承的,多重继承时代子类拥有多重特征

 class Person(object):
@staticmethod
def pursuit_happiness():
print("幸福是奋斗出来的!") class Father(Person):
character = "温和,坚韧" class Mather(Person):
interest = "阅读,文艺竞技" class Student(Person):
@staticmethod
def do_homework():
print("是学生就要做作业!") class Son(Father, Mather, Student): # 多重继承
pass s = Son()
# Son类实例具有了Father类的属性
print(s.character) # 输出:温和,坚韧
# Son类实例具有了Mather类的属性
print(s.interest) # 输出:阅读,文艺竞技
# Son类实例具有了Student类的方法
s.do_homework() # 输出:是学生就要做作业!
# 由于Father类,Mather类,Student类都各自继承了Person类,所以Son类也有Person类的方法
s.pursuit_happiness() # 输出:幸福是奋斗出来的!

  - 类的组合使用

 class Car(object):
def __init__(self, color, owner):
self.color = color
self.owner = owner class House(object):
def __init__(self, location, owner):
self.location = location
self.owner = owner class Person(object):
def __init__(self, name, car=None, house=None):
self.name = name
self.car = car
self.house = house per1 = Person("Stanley") # 实例化Person
c = Car("Black", per1) # 实例化Car
h = House("China", per1) # 实例化House
per1.car = c # 把实例化的car给per1
per1.house = h # 把实例化的house给per1 # 通过person访问car的属性
print(per1.car.color) # 输出:Black
# 通过person访问house的属性
print(per1.house.location) # 输出:China
# 通过house和car访问person的属性
print(h.owner.name) # 输出:Stanley
print(c.owner.name) # 输出:Stanley

本文参考:

  [美]Bill Lubanovic 《Python语言及其应用》
  https://www.liaoxuefeng.com 廖雪峰的官方网站