python 属性全部语法
核心逻辑:拦截
目标:保护数据
1. 读 + 写属性 快捷键:props + 回车
class Wife:
def init(self, age=0):
self.age = age
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
self.__age = value
w01 = Wife(25)
print(w01.age)
2. 读 属性 快捷键:prop + 回车
class Wife:
def init(self):
# 数据从何而来,无所谓(可以从参数来、某个方法来、写死).
self.__age = 25
@property
def age(self):
return self.__age
w01 = Wife()
print(w01.age)
w01.age = 222
3. 写 属性 快捷键:prop + 回车
class Wife:
def init(self, age=0):
self.age = age
age = property()
@age.setter# age.setter(…)
def age(self, value):
self.__age = value
class Wife:
def init(self, age=0):
self.age = age
def age(self, value):
self.__age = value
age = property(None,age)
# w01 = Wife(25)
# print(w01.dict)
# print(w01.age)
设计角度讲
1. 定义:
(1) 分而治之
将一个大的需求分解为许多类,每个类处理一个独立的功能。
(2) 变则疏之
变化的地方独立封装,避免影响其他类。
(3) 高 内 聚
类中各个方法都在完成一项任务(单一职责的类)。
(4) 低 耦 合
类与类的关联性与依赖度要低(每个类独立),让一个类的改变,尽少影响其他类。
2. 优势:
便于分工,便于复用,可扩展性强。
# 类与类行为不同
# 对象与对象数据不同
# 需求:老张开车去东北
# 变化:老张、老李、老王… --> 数据不同
# 划船、骑车、飞机… --> 行为不同
# 西北、南北… --> 数据不同
写法1
# 语义:老张去东北创建一辆新车
# 老张无论去哪里,都会创建一辆新车
class Person:
def init(self, name=""):
self.name = name
def go_to(self,position):
print(self.name,“去”,position)
car = Car()
car.run()
class Car:
# 实例成员:对象.?
def run(self):
print(“汽车行驶”)
lz = Person(“老张”)
lz.go_to(“东北”)# 一辆新车
lz.go_to(“家”)# 又一辆新车
写法2
语义:老张开车自己的车去东北
class Person:
def init(self, name=""):
self.name = name
self.car = Car()
def go_to(self,position):
print(self.name,"去",position)
self.car.run()
class Car:
def run(self):
print(“汽车行驶”)
lz = Person(“老张”)
lz.go_to(“东北”)
lz.go_to(“家”)
写法3
# 语义:老张通过传递的参数,决定如何去东北.
class Person:
def init(self, name=""):
self.name = name
def go_to(self, vehicle, position):
print(self.name, “去”, position)
vehicle.run()
class Car:
def run(self):
print(“汽车行驶”)
lz = Person(“老张”)
bm = Car()
lz.go_to(bm, “东北”)
练习1:
"""
需求:小明在银行取钱
现象:人的钱多了, 银行的钱少了
"""
class Person:
def __init__(self, money):
self.money = money
class Bank:
def __init__(self, money):
self.money = money
def draw_money(self, person, value):
self.money -= value # 银行钱少了
person.money += value # 人钱多了
xm = Person(0)
zsyh = Bank(100000)
zsyh.draw_money(xm, 5000)
print("小明的钱", xm.money)
print("银行的钱", zsyh.money)
练习2:
"""
需求:玩家(攻击力)攻击敌人(血量),
敌人受伤(减血)后可能死亡(播放死亡动画)
"""
class Person:
def __init__(self, name="", atk=0):
self.name = name
self.atk = atk
def attack(self, enemy):
enemy.damage(self.atk)
class Enemy:
def __init__(self, hp=0):
self.hp = hp
def damage(self, atk):
self.hp -= atk
if self.hp <= 0:
self.__death()
def __death(self):
print("播放死亡动画")
xm = Person("关羽", 50)
xb = Enemy(50)
xm.attack(xb)
练习3:
"""
张无忌教赵敏九阳神功
赵敏教张无忌化妆
张无忌上班挣了8000元
赵敏上班挣了10000元
"""
class Person:
def __init__(self, name=""):
self.name = name
def teach(self, person_other, skill):
print(self.name, "教", person_other.name, skill)
def work(self, salary):
print(self.name, "上班挣了", salary, "元")
zwj = Person("张无忌")
zm = Person("赵敏")
zwj.teach(zm, "九阳神功")
zm.teach(zwj, "化妆")
zwj.work(8000)
zm.work(10000)