封装
私有属性
class Teacher:
__identifier = 'Teacher' #私有静态属性
def __init__(self,name,pwd)
self.name = name
self.__pwd = pwd #私有属性 内部使用,外部不能使用
def pwd(self):
print(self.__pwd)
alex = Teacher('alex','3714')
alex.pwd()
class Teacher:
__identifier = 'Teacher'
def __init__(self,name,pwd)
self.name = name
self.__pwd = pwd
self.__p()
def __p(self):
print(self.__pwd)
alex = Teacher('alex','3714')
print(Teacher._teacher__identifier)
class Teacher:
def __init__(self,name,pwd)
self.name = name
self.__pwd = pwd
self.__p()
def __p(self): #私有方法
print(self.__pwd)
alex = Teacher('alex','3714')
alex._teacher__p()
class Teacher:
__identifier = 'Teacher'
def __init__(self,name,pwd):
self.name = name
self.__pwd = pwd
self.__p()
def __p(self):
return hash(self.__pwd)
def login(self,password)
return hsah(password) == self.__pwd
alex = Teacher('alex','3714')
ret = alex.login('3714')
print(ret)
私有方法
class Foo:
def __dahong_sb(self)
print('Foo')
class Son(Foo):
def __ddahong_sb(self):
print('Son')
def func(self):
self.__dahong_sb()
son = Son()
son.func()
1.有一些方法的返回值只是用来作为中间结果
2.父类的方法不希望子类继承
拾遗
from collections import namedtuple
Point = namedtuple('point',['x','y'])
t1 = Point(1,2)
print(t1.x)
print(t1.y)
#没有方法并且属性不会发生变化的类
#定义简单
#不能改变
私有属性:
成人的BMI数值
过轻:低于18.5
正常:18.5 - 23.9
过重:24 - 27
肥胖:28 - 32
非常肥胖,高于32
体质指数(BMI) = 体重(Kg)/身高^2(m)
class Person:
def __init__(self,name,height,weight):
self.name = name
self.__height = height
self.__weight = weight
def get_bmi(self):
return self.__weight / (self.__height*self.__height)
def change_weight(self,new_weight):
if new_weight > 20:
self.__weight = new_weight
else:
print('体重过轻')
# jinghong = Person('景弘',1.81,94)
# print(jinghong.get_bmi())
# jinghong.change_weight()
# print(jinghong.get_bmi())
练习:
房屋:
业主、长、宽、面积
class House:
def __init__(self,yezhu,chang,kuan):
self.name = yezhu
self.__chang = chang
self.__kuan = kuan
def area(self):
return self.__chang * self.__kuan
yezhu = House('xujing',112,240)
print(yezhu.area())
用装饰器描述的几个方法:
@property 把一个方法伪装成属性
class Person:
def __init__(self,name,height,weight):
self.name = name
self.__height = height
self.__weight = weight
@property
def get_bmi(self):
return self.__weight/(self.__height*self.__height)
hong = Person('hong',1.8,94)
print(hong.name,hong.bmi)
class Shop:
# discount = 0.75
# def __init__(self,name,price):
# self.name = name
# self.__price = price
# @property #!!!
# def price(self):
# return self.__price * Shop.discount
# @price.setter #!
# def price(self,new_price):
# self.__price = new_price
#
# apple = Shop('apple',5)
# apple.price = 6
# print(apple.__dict__)
# print(apple.price)
@staticmethod
class A:
def __init__(self,name)
self.name = name
@staticmethod
def func():
print('func')
A.func()
不能讲函数独立的放在类外面,完全使用面向对象编程的时候
并且这个函数完全不需要依赖对象的属相和类的属性
就可以用staticmethod装饰这个函数
静态方法:没有必须传的参数,方法不需要用对象的属性和类的属性
类方法:必须传一个类,方法不需要使用对象的属性,但可以使用类的属性
@classmethod
class A: role = 'a' @classmethod def class_method(cla): print(cla.role) A.class_method() A.role()
普通方法:必须传一个对象,可以使用对象的属性和类的属性