Package
Broadly: the property or method loaded up, you can not call outside, through the name of the class to call
Narrow: The property or method to hide, can not call out, and can only be used inside secretly
Give a name preceded by a double-underlined when the name became a private
class User: __country = 'China' def __init__(self,name,passwd): self.usr = name self.__pwd = passwd # 私有的实例变量/私有的对象属性 def func(self): print(__country) alex = User('alex','sbsbsb') print(alex.__pwd) # 报错 print(alex.pwd) # 报错 print(User.__country) # 报错 alex.func() # China ''' 解析:设置私有的实例变量或私有的对象属性后,无法通过正常的查看属性方法的方式对其查看。 '''
View private instance variables or private property
The method of obtaining the private instance variables : We can define within a class method, this private instance variables as the return value of a function, so that we can retrieve the value returned by calling this method, so as to obtain the private instance variables.
Methods of obtaining private method : We can perform this private method, ** self .__ name () **, as a return value directly returned within the definition of a class method in this method.
import hashlib class User: def __init__(self,name,passwd): self.usr = name self.__pwd = passwd # 私`有的实例变量 def __get_md5(self): # 私有的绑定方法 md5 = hashlib.md5(self.usr.encode('utf-8')) md5.update(self.__pwd.encode('utf-8')) return md5.hexdigest() def getpwd(self): return self.__get_md5() alex = User('alex','sbsbsb') print(alex.getpwd()) ''' 解析:我们在私有方法__get_md5中针对用户名密码加密,当想在类的外部查看时,可以通过对象名.getpwd()查看加密后的结果. '''
Private principles:
When we add __ in front of the definition of static variable or method, stored in memory is the current name of the class of words where the fight in the private variable, so we are finding out in the outside, but can not be defined in an external private concept. And when we use within the class automatically to the current sentence where the class name is spelled in private variables before the completion of the deformation, it can be manipulated.
class Foo(object): def __init__(self): self.__func() def __func(self): print('in Foo') class Son(Foo): def __func(self): print('in Son') Son() ''' in son 当前这句话所在的类的名字拼在私有变量前完成变形,即__init__所在的类Foo,所以执行的是Foo中的__func '''
Note: proprietary content can not be used by subclasses!
class Foo(object): def __func(self): print('in Foo') class Son(Foo): def __init__(self): self.__func() Son() ''' 报错 因为在Son空间中没有__func。(只在本类的空间) '''
在其他语言中的数据的级别都有哪些?在python中有哪些? public 公有的 类内类外都能用,父类子类都能用 python支持 protect 保护的 类内能用,父类子类都能用,类外不能用 python不支持 private 私有的 本类的类内部能用,其他地方都不能用 python支持
Using proprietary three cases
Let you see make you change
See can not be changed (the internal implementation of the class)
To see can be changed (the internal implementation of the class)
Package syntax
Private static variable
Private instance variable
Proprietary binding method
Proprietary features
May be used within the class
You can not be used outside the class
Can not be used in a subclass of the class
principle
Deformation: The current name of the class of words where the fight before the complete deformation private variables
When deformed inside the class definition
Level class variables
A total of python support
Protection does not support python
Private support python
Class three decorator (built-in function)
property
- To a method (no parameters) disguised as a property, for example:
from math import pi class Circle: def __init__(self,r): self.r = r @property # 把一个方法伪装成一个属性,在调用这个方法的时候不需要加()就可以直接得到返回值 def area(self): return pi * self.r**2 c1 = Circle(5) print(c1.r) print(c1.area) ''' 解析:@property把一个方法伪装成一个属性,在调用这个方法的时候不需要加()就可以直接得到返回值 如上式中我们想查看c1的面积只需要c1.area就可,省略了() '''
The second scenario: cooperative and private property
class Goods: discount = 0.8 def __init__(self,name,origin_price): self.name = name self.__price = origin_price @property def price(self): return self.__price * self.discount apple = Goods('apple',5) print(apple.price) # 4.0
Advanced - Changes to private property
class Goods: discount = 0.8 def __init__(self,name,origin_price): self.name = name self.__price = origin_price @property def price(self): return self.__price * self.discount @price.setter # 装饰器 def price(self,new_value): if isinstance(new_value,int): self.__price = new_value @price.deleter def price(self): del self.__price apple = Goods('apple',5) print(apple.price) # 调用的是被@property装饰的price apple.price = 10 # 调用的是被setter装饰的price print(apple.price) del apple.price # 调用的是被deleter装饰的prcie (并不能真正删除什么,而是调用此方法,此方法内部有删除price的代码而已。 ''' 4.0 8.0 '''
classmethod - decorated methods become class methods
Action: A method to bind an object, class methods modified to a
advantage:
- In the method can still refer to a static variable in the class
- You can not instantiate an object, you use the class name to call this method directly outside
- By class name calling method, you can also call the method by object name
When to use:
- It defines a method, default to wear self, but the self is not in use
- And you use this method in the current class name, or are you going to use this kind of memory space in the name of the time
class Goods: __discount = 0.8 def __init__(self): self.__price = 5 self.price = self.__price * self.__discount @classmethod # 把一个对象绑定的方法 修改成一个 类方法 def change_discount(cls,new_discount): cls.__discount = new_discount Goods.change_discount(0.6) # 类方法可以通过类名调用 apple = Goods() print(apple.price) apple.change_discount(0.5) # 类方法可以通过对象名调用 apple2 = Goods() print(apple2.price) ''' 3.0 2.5 '''
Examples of some understanding! !
import time class A: def __init__(self,year,month,day): self.year = year self.month = month self.day = day @classmethod def today(cls): year = time.localtime().tm_year month = time.localtime().tm_mon day = time.localtime().tm_mday return cls(year,month,day) t_day = A.today() print(t_day.year,t_day.month,t_day.day) # 2019 6 5
staticmethod - garnished method will become a static method
Effect: the class a common function to be used directly moved, a method of manufacturing a static
When to use: in itself is a normal function, the internal implementation of the class you want to move to, then added directly to this function @staticmethod decorator on it.
Inside the function of both self variables will not be used, it will not be used cls class
class User: pass @staticmethod def login(a,b): # 本身是一个普通的函数,被挪到类的内部执行,那么直接给这个函数添加@staticmethod装饰器就可以了 print('登录的逻辑',a,b) # 在函数的内部既不会用到self变量,也不会用到cls类 obj = User() User.login(1,2) obj.login(3,4) ''' 登录的逻辑 1 2 登录的逻辑 3 4 '''
You can define the content class:
class A: country = '中国' def func(self): print(self.__dict__) @classmethod def clas_func(cls): print(cls) @staticmethod def stat_func(): print('普通函数') @property def name(self): return 'wahaha'
Static variables - is shared by all objects in a variable called by the object / class.
Bound method - a function that comes with self argument invoked by objects
Class Method - cls parameter is a function call that comes from the object / class
Static methods - is an ordinary function with nothing by the object / class call
property property: is a property method is called disguised by the object, but not brackets
反射 ( getattr() hasattr())
Definition: string data type name, the function to operate \ instance variables \ binding method and the like corresponding to the name
When to use: knowing a variable string data type the name you want to call him directly, but you can not tune
Scenario:
- Reflecting object instance variables
- Static class variable reflective / binding method / other methods
- Module all the variables
- Module introduced module
- py file currently executing - Script
For example:
- This script class reflection method or instance variables
class Person: def __init__(self,name,age): self.name = name self.age = age def qqxing(self): print('in qqxing') alex = Person('alex',83) wusir = Person('wusir',74) ret = getattr(alex,'name') print(ret) # alex ret = getattr(wusir,'qqxing') # in qqxing ret() ''' 解析:我们创建一个类alex,当我查看alex中的变量及方法须使用alex.想查看的内容 但如果查看的内容如果是一个待输入的即字符串类型,我们无法执行。 此时,我们可以使用getattr(alex,想查看的内容) 《=》alex.想查看的内容(去除字符串格式后) '''
Reflected in the imported module class
import a print(getattr(a, 'Alipay')) print(getattr(a, 'Wechat')) # 导入模块a中的类的内存地址,可以在其后加()按照格式创建对象
Class, function names, variables, etc. in the reflection of the current script
import sys s1 = '加油老哥们!' class Person: def __init__(self,name,age): self.name = name self.age = age print(getattr(sys.modules['__main__'],'s1')) ret = getattr(sys.modules['__main__'],'Person') nie = ret('alex',18) print(nie.__dict__)
Hsattr ()
When we use getattr (), if the error will not be found, so before use you should first determine we are looking for the corresponding method or variable exists.
callable when we want to enter the content of our operation, but do not know its corresponding method, function, or variable, so this time we need to determine if it can be called, can call on the increase () after, or without
class A: Role = '治疗' def __init__(self): self.name = 'alex' self.age = 84 def func(self): print('wahaha') a = A() print(hasattr(a,'sex')) # False print(hasattr(a,'age')) # True print(hasattr(a,'func')) # True if hasattr(a,'func'): ————》此时为True if callable(getattr(a,'func')): ————》func为方法,可调用 getattr(a,'func')() ————》 所以调用func
- Some built-in magic methods
__new__
! ! ! ! ! (Construction method)Role: Create a space object is needed
In instantiated to create an object space, there is a pointer to the class category ->
__new__
before calling__init__
.class A: def __new__(cls, *args, **kwargs): # 构造方法 # o = super().__new__(cls) o = object.__new__(cls) # 寻找父类中__new__方法并创建一个class A的对象 print('执行new',o) return o # 返回在父类中得到的对象 def __init__(self): # __init__接收到__new__返回的对象给予self print('执行init',self) A() ''' 解析:当我们实例化A时,总是先执行__new__方法,而方法中的内容为寻找并执行父类(object类)的__new__方法,把返回的对象赋予给__Init__的self并执行__init__的函数。 '''
Design Patterns - single-case model (a class from start to finish will create a space of self)
\class A: __statu = None def __new__(cls, *args, **kwargs): if not cls.__statu: cls.__statu = super().__new__(cls) return cls.__statu def __init__(self,name,age): self.name = name self.age = age person = A('NIE',18) print(person.name,person.age) # NIE 18 person2 = A('sui',18) print(person.name,person.age) # sui 18 print(person2.name,person2.age) # sui 18 ''' 解析:类中设置了一个私有的静态变量 __statu = None,在进行实例化时先执行A类中的__new__方法,判断__statu是否为空如果为空,则寻找并执行父类的__new__方法,开辟了一个空间,创建了一个A类的对象,并重新赋值给 __statu,当再次实例化时__statu已被赋值,所以不会重新开辟空间创建对象。所以所有A类的对象都使用同一个空间。 '''
import are introduced in python singleton
__call__
When an object is determined () is executable using callable (object), which is performed inside the object
__call__
method.__len__
Gets the object length. When using the len (object) is performed inside an object
__len__
methodclass Cls: def __init__(self,name): self.name = name self.students = [] def len(self): return len(self.students) def __len__(self): return len(self.students) py22 = Cls('py22') py22.students.append('杜相玺') py22.students.append('庄博') py22.students.append('大壮') print(py22.len()) # 3 调用类的绑定方法 print(len(py22)) # 3 调用内置函数
__str__
with__repr__
Role: both aim for an explicit display objects necessary information for easy viewing and debugging.
Usage scenarios: When I want to print objects to want to get some information about the object. Direct printing can not be completed at this time.
note:
- Only a printing object print ()% s string with stitching or str (object) always call this object
__str__
methods __str__
Only return a string, a plurality of return when the information needs to be spliced.
The following example:. ',' Join ([self.name, str (self.price), self.period])
class Course: def __init__(self,name,price,period): self.name = name self.price = price self.period = period def __str__(self): return ','.join([self.name,str(self.price),self.period]) # 字符串拼接 python = Course('python',21800,'6 months') linux = Course('linux',19800,'5 months') mysql = Course('mysql',12800,'3 months') go = Course('go',15800,'4 months') print(go) # go,15800,4 months print(python) # python,21800,6 months print(mysql) # mysql,12800,3 months lst = [python, linux, mysql, go] for index,c in enumerate(lst,1): print(index,c) num = int(input('>>>')) course = lst[num-1] print('恭喜您选择的课程为 %s 价格%s元'%(course.name,course.price))
- Only a printing object print ()% s string with stitching or str (object) always call this object
__repr__
__repr__不仅是__str__的替代品,还有自己的功能 用%r进行字符串拼接 或者用repr(对象)的时候总是调用这个对象的__repr__方法
class clas: def __init__(self): self.student = [] def append(self,name): self.student.append(name) def __repr__(self): return str(self.student) def __str__(self): return 'aaa' py22 = clas() py22.append('大壮') print(py22) # aaa 执行__str__ print(str(py22)) # aaa 执行__str__ print('我们py22班 %s'%py22) # 我们py22班 aaa 执行__str__ print('我们py22班 %r'%py22) # 我们py22班 ['大壮'] print(repr(py22)) # ['大壮']