Day 26 python 学习笔记:面向对象(5), 封装,property, classmethod, staticmethod

Part 1:

1 from collections import namedtuple           # 命名的元组相当于一个不能被改变属性的类
2 Point = namedtuple('point',['x','y'])
3 t1 = Point(1,2)
4 print(t1.x)
5 print(t1.y)
6 # 没有方法并且属性不会发生变化的类
7     # 定义简单
8     # 不能改变

 

Part 2: 私有属性和私有方法

 1 class Teacher:
 2     __identifier = 'Teacher'        # 私有静态属性
 3     def __init__(self,name,psd):     # 私有动态属性
 4         self.name = name
 5         self.__psd = psd
 6 
 7     def __func(self):               # 私有方法
 8         return hash(self.__psd)
 9 
10     def login(self,password):       # 普通方法
11         return hash(password) == self.__func()
12 
13 p1 = Teacher('alex',3714)
14 print(p1._Teacher__identifier)        # “后门”
15 print(p1._Teacher__psd)               # “后门”
16 print(p1.login(3714))                 # True
17 print(p1.login(3741))                 # False

Part 3: 通过编写函数更改私有属性

 1 class Person:
 2     def __init__(self,name,hight,weight):
 3         self.name = name
 4         self.__hight = hight
 5         self.__weight = weight
 6 
 7     def get_bmi(self):
 8         return self.__weight / self.__hight ** 2
 9 
10     def change_weight(self,new_weight):
11         if self.__weight >0: self.__weight = new_weight
12         else:print("不合法的体重")
13 
14 alex = Person('alex',1.7,60)
15 print(alex.get_bmi())
16 alex.change_weight(70)
17 print(alex.get_bmi())

Part 4: 用 @property 装饰器把方法伪装成属性,以符合“统一调用原则”

 1 class House:
 2     def __init__(self,width,length):
 3         self.__width = width
 4         self.__length = length
 5 
 6     @property                                            # area = property(area)
 7     def area(self):
 8         return self.__length * self.__width
 9 
10 h = House(3.3,3)
11 print(h.area)
12 h._House__width = 3.5
13 print(h.area)

Part 5: 用 @.setter 装饰器另私有属性可变

 1 class Market:
 2     discount = 0.75
 3     def __init__(self,name,price):
 4         self.name = name
 5         self.__price = price
 6 
 7     @property
 8     def foo(self):
 9         return self.__price * Market.discount
10 
11     @foo.setter
12     def foo(self,new_price):
13         self.__price = new_price
14 
15 apple = Market('apple',8)
16 print(apple.foo)
17 apple.foo = 6
18 print(apple.__dict__)
19 print(apple.foo)

Part 6: 类对象调用的方式

1 class A:
2     def __init__(self,name):
3         self.name = name
4 
5     def func(self):   #self形式参数  普通方法、绑定(对象)方法
6         print('func')
7 
8 a = A('alex')
9 a.func()  # 等价于 A.func(a)
 1 class Manager:
 2 
 3     @staticmethod    #静态方法
 4     def create_student(): pass
 5 
 6     # 不能将函数独立的放在类外面 完全使用面向对象编程的时候
 7     # 并且这个函数完全不需要依赖对象的属性和类的属性
 8     # 就可以用staticmethod装饰这个函数
 9 
10 # print(Manager.create_student)

Part 7:  利用 @classmethod 使得类对象可以调用动态属性

1 class A:
2     role = 'a'
3     @classmethod
4     def class_method(cls):  # 这里的 cls 是规定写法,潜规则
5         print(cls.role)
6 
7 A.class_method()  # 等价于:A.role

 

posted @ 2017-09-20 16:02  折翼的壕哥  阅读(44)  评论(0)    收藏  举报