python面向对象之装饰器
python面向对象之装饰器
一、绑定方法 绑定方法分为2种: class Student(): def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender # 绑定给对象的方法,对象来调用,会把自己当成第一个参数传到函数里面self def tell_info(self): print('name: %s,age:%s, gender:%s' % (self.name, self.age, self.gender)) stu = Student('ly', 18, 'male') # print(stu.name) stu.tell_info() # stu.tell_info(stu) 2. 绑定给类的 class Mysql(): def __init__(self, ip, port): self.ip = ip self.port = port @classmethod # 该方法绑定给类了,以后有类来调用,会自动把类名当成第一个参数传过来,cls def from_conf(cls): # cls => Oracle # obj = Oracle(settings.IP, settings.PORT) obj = cls(settings.IP, settings.PORT) return obj Mysql.from_conf() 二、非绑定方法(静态方法)
既不绑定给类,也不绑定给对象 class Student(): school = 'SH' def __init__(self, name, age): self.name = name self.age = age @staticmethod # 静态方法 def create_id(): import uuid return uuid.uuid4() stu = Student('ly', 18) # print(stu.create_id()) # print(Student.create_id()) print(stu.create_id()) 三、如何隐藏属性# 1. 如何隐藏 ''' 为什么要隐藏: 类里面的隐藏属性, 类外部可以使用,但是目的不是让类外部使用的,类外部要是想用,在类内部开放接口进行访问
class Student(): __school = 'SH' # _Student__school => _类名__属性名 def __init__(self, name, age): self.__name = name self.age = age def __tell_info(self): # _Student__tell_info => _类名__函数名 print('name: %s, age: %s' % (self.__name, self.age)) def get_school(self): return self.__school # self._Student__school def set_school(self, v): if type(v) is not str: print('数据类型不合法') # if isinstance(v, str): return self.__school = v 四、
class Student(): __school = 'SH' # _Student__school => _类名__属性名 def __init__(self, name, age): self.__name = name self.age = age def __tell_info(self): # _Student__tell_info => _类名__函数名 print('name: %s, age: %s' % (self.__name, self.age)) @property # 把方法伪装成属性 def name(self): return "name:%s" % self.__name @name.setter def name(self, v): if type(v) is not str: print('数据类型不合法') # if isinstance(v, str): return self.__name = v @name.deleter def name(self): print('不让删') stu = Student('ly', 18) print(stu.get_name()) stu.name = 123 print(stu.name) del stu.name # 练习 class Bmi(): def __init__(self, height, weight): self.height = height self.weight = weight @property def get_bmi(self): return self.weight / (self.height ** 2) bmi = Bmi(1.8, 70) print(bmi.get_bmi) # 了解 class Student(): __school = 'SH' # _Student__school => _类名__属性名 def __init__(self, name, age): self.__name = name self.age = age def __tell_info(self): # _Student__tell_info => _类名__函数名 print('name: %s, age: %s' % (self.__name, self.age)) def get_name(self): return "name:%s" % self.__name def set_name(self, v): if type(v) is not str: print('数据类型不合法') # if isinstance(v, str): return self.__name = v def del_name(self): print('不让删') # 了解 name = property(get_name, set_name, del_name) stu = Student('ly', 18) # print(stu.xxx) stu.name = 'aaa' print(stu.name) ------------------------------今日内容就到这里了,我们下次再见--------------------------------- |