A reflection
The concept is reflected by Smith in 1982 first proposed, mainly it refers to the program can access, the ability to detect and modify its own state or behavior (introspection). It puts forward the concept quickly led to research on the application of computer science reflective. It was first used in the field of programming language design, and has made achievements in Lisp and object-oriented aspects.
python reflective object-oriented: the object-related properties operated by a string. Everything is an object in python (could use reflection)
Four function can be achieved introspective
The following method is applicable to classes and objects (everything is an object, the class itself is a target)
Exemplary object instantiation
class Foo:
f = '类的静态变量'
def __init__(self,name,age):
self.name=name
self.age=age
def say_hi(self):
print('hi,%s'%self.name)
obj=Foo('egon',73)
#检测是否含有某属性
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))
#获取属性
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()
print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
#设置属性
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))
#删除属性
delattr(obj,'age')
delattr(obj,'show_name')
delattr(obj,'show_name111')#不存在,则报错
print(obj.__dict__)
Reflection of the object
class Foo(object):
staticField = "old boy"
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
@staticmethod
def bar():
return 'bar'
print getattr(Foo, 'staticField')
print getattr(Foo, 'func')
print getattr(Foo, 'bar')
Reflection of the class
import sys
def s1():
print 's1'
def s2():
print 's2'
this_module = sys.modules[__name__]
hasattr(this_module, 's1')
getattr(this_module, 's2')
Reflected current module
#一个模块中的代码
def test():
print('from the test')
"""
程序目录:
module_test.py
index.py
当前文件:
index.py
"""
# 另一个模块中的代码
import module_test as obj
#obj.test()
print(hasattr(obj,'test'))
getattr(obj,'test')()
Reflecting light of other modules
Reflection of applications:
Learn the four functions of reflection. Then the reflection in the end what use is it? What is its scenario is it?
Now let's open a browser and visit a website, you click to jump to the login screen to log on, you click Register Jump to register interface, and so on, in fact you actually click one of the links, each Links will have a function or method to deal with.
class User:
def login(self):
print('欢迎来到登录页面')
def register(self):
print('欢迎来到注册页面')
def save(self):
print('欢迎来到存储页面')
while 1:
choose = input('>>>').strip()
if choose == 'login':
obj = User()
obj.login()
elif choose == 'register':
obj = User()
obj.register()
elif choose == 'save':
obj = User()
obj.save()
Previous solution did not learn reflection
class User:
def login(self):
print('欢迎来到登录页面')
def register(self):
print('欢迎来到注册页面')
def save(self):
print('欢迎来到存储页面')
user = User()
while 1:
choose = input('>>>').strip()
if hasattr(user,choose):
func = getattr(user,choose)
func()
else:
print('输入错误。。。。')
After studying reflection solution
How simple glance.
II. Functions vs Methods
Learned here, I was finally able to answer you may have been a question. That is, the previous study we call len () is a function (called methods when the slip of the tongue) has said is as strip str way, that in the end what is it called? Functions and methods What are the differences and similarities? I am here on an official explanation.
2.1 is determined by printing functions (methods) name
def func():
pass
print(func) # <function func at 0x00000260A2E690D0>
class A:
def func(self):
pass
print(A.func) # <function A.func at 0x0000026E65AE9C80>
obj = A()
print(obj.func) # <bound method A.func of <__main__.A object at 0x00000230BAD4C9E8>>
View Code
2.2 verified by module types
from types import FunctionType
from types import MethodType
def func():
pass
class A:
def func(self):
pass
obj = A()
print(isinstance(func,FunctionType)) # True
print(isinstance(A.func,FunctionType)) # True
print(isinstance(obj.func,FunctionType)) # False
print(isinstance(obj.func,MethodType)) # True
2.3 is a function of the static method
from types import FunctionType
from types import MethodType
class A:
def func(self):
pass
@classmethod
def func1(self):
pass
@staticmethod
def func2(self):
pass
obj = A()
# 静态方法其实是函数
# print(isinstance(A.func2,FunctionType)) # True
# print(isinstance(obj.func2,FunctionType)) # True
2.4 the difference between the function and method
So, in addition to the above-mentioned functions and methods are different, we have summarized the following points difference.
(1) function is explicitly pass data. If we want to indicate as len () function to pass some data to be processed.
(2) function has nothing to do with the object.
Data (3) method is implicitly transmitted.
(4) The method of operating data of the internal classes.
(5) method is associated with the object. As we is and is not a call is to strip () method str objects, such as we have a string s, then s.strip () called with. Yes, strip () method belongs to the object str.
Perhaps we will be in daily colloquial loose when calling functions and methods, but our hearts to know the difference between the two.
In other languages, such as Java methods only, C only functions, C ++ it, it depends on whether the class.
III. The method of the bis
Definition: The Double Down is a special method, his method is of special significance interpreter provided by the method name plus cool underscore double underlined name __ __ method, the method is to double down python-source programmers, we Do not try to double down method under development, but further research methods double, more beneficial to us to read the source code.
Call: double under different methods have different trigger modes, like the same organs triggered when Tomb, unknowingly triggered a two-under method, for example: init
1.3 __len
class B:
def __len__(self):
print(666)
b = B()
len(b) # len 一个对象就会触发 __len__方法。
class A:
def __init__(self):
self.a = 1
self.b = 2
def __len__(self):
return len(self.__dict__)
a = A()
print(len(a))
3.02 __hash
class A:
def __init__(self):
self.a = 1
self.b = 2
def __hash__(self):
return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))
3.03 str
If a class is defined __str__ method, then when the print target, the method returns the default output value.
class A:
def __init__(self):
pass
def __str__(self):
return '太白'
a = A()
print(a)
print('%s' % a)
3.04 repr
If a class is defined __repr__ method, then at repr (object), the method returns a default output value.
class A:
def __init__(self):
pass
def __repr__(self):
return '太白'
a = A()
print(repr(a))
print('%r'%a)
3.05 call
Brackets behind the object, trigger the execution.
Note: the constructor is executed by the __new__ is triggered to create an object, namely: class name = Object (); for the call is performed by the method of the object triggers the brackets, namely: Object () or class () ( )
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = Foo() # 执行 __init__
obj() # 执行 __call__
3.06 __eq
class A:
def __init__(self):
self.a = 1
self.b = 2
def __eq__(self,obj):
if self.a == obj.a and self.b == obj.b:
return True
a = A()
b = A()
print(a == b)
3.07 of the
Destructor, when the object is released in the memory, automatically trigger the execution.
Note: This method is generally no need to define, because Python is a high-level language, programmers used without concern allocate and free memory, because this work is to the Python interpreter to execute, so call the destructor is triggered automatically performed at the time garbage collector by an interpreter.
3.08__new
class A:
def __init__(self):
self.x = 1
print('in init function')
def __new__(cls, *args, **kwargs):
print('in new function')
return object.__new__(A, *args, **kwargs)
a = A()
print(a.x)
class A:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
obj = object.__new__(cls)
cls.__instance = obj
return cls.__instance
Singleton
Singleton specific analysis
Singleton pattern is a common software design patterns. In its core structure contains only a single embodiment is referred to a particular class category. Example ensures single mode systems only one instance of a class instance and the easy access to the outside, so as to facilitate control of the number of instances and save system resources. If you want a class of objects in the system can only be one, singleton pattern is the best solution.
[Single-case model motive, reason]
for certain types of systems, only one instance is important, for example, a system can contain multiple print job, but can only have a job are working; a system only You can have a window manager or a file system; a system can have a timing device or ID (number) generator. As in Windows, you can only open a task manager. If you do not use the mechanism of the window object uniquely, multiple windows pop up, if the contents of these windows display exactly the same, it is the duplicate object, a waste of memory resources; inconsistent content if the window is displayed, it means that in a moment the system has multiple states, inconsistent with the actual, misunderstanding will bring to the user, do not know which one is the real state. So sometimes the system to ensure the uniqueness of an object that is a class only one instance is very important.
How to ensure that only one instance of a class, and this instance is easy to access it? Define a global variable can be sure that the object can be accessed at any time, but can not prevent us instantiate multiple objects. A better solution is to let the only instance of the class itself responsible for saving it. This class can ensure that no other instance is created, and it can provide a method to access the instance. This is the motivation mode Singleton pattern.
[Singleton] advantages and disadvantages
[advantage]
First, the control instance
Singleton pattern will prevent other objects instantiate a copy of its own singleton object, so as to ensure that all objects have access to a unique instance.
Second, the flexibility
because the control class instantiation process, so the flexibility to change the class instantiation process.
[Shortcomings]
First, overhead
Although few in number, but will check whether there are instances of the class if every object request references, would still require some overhead. Initialization can solve this problem by using static.
Second, the possible development of confusion
when using the singleton object (especially the objects defined in the class library), developers must keep in mind that they can not use the new keyword to instantiate an object. Because you may not access library source code, so application developers may find themselves unexpectedly can not be directly instantiated.
Third, object lifetime
can not solve the problem delete a single object. Providing memory management language (e.g., based on the language of the .NET Framework), it can result in only a single instance of the class embodiment is unassigned because it contains a reference to the instance private. In some languages (e.g., C ++), other class instance object can be deleted, but this will lead to the suspension of the references appear singleton
3.09 __item__ series
class Foo:
def __init__(self,name):
self.name=name
def __getitem__(self, item):
print(self.__dict__[item])
def __setitem__(self, key, value):
self.__dict__[key]=value
def __delitem__(self, key):
print('del obj[key]时,我执行')
self.__dict__.pop(key)
def __delattr__(self, item):
print('del obj.key时,我执行')
self.__dict__.pop(item)
f1=Foo('sb')
f1['age']=18
f1['age1']=19
del f1.age1
del f1['age']
f1['name']='alex'
print(f1.__dict__)
3.10 related context manager
enter __exit
# 如果想要对一个类的对象进行with as 的操作 不行。
class A:
def __init__(self, text):
self.text = text
with A('大爷') as f1:
print(f1.text)
They did not operate like this
class A:
def __init__(self, text):
self.text = text
def __enter__(self): # 开启上下文管理器对象时触发此方法
self.text = self.text + '您来啦'
return self # 将实例化的对象返回f1
def __exit__(self, exc_type, exc_val, exc_tb): # 执行完上下文管理器对象f1时触发此方法
self.text = self.text + '这就走啦'
with A('大爷') as f1:
print(f1.text)
print(f1.text)
There they can do this
class Diycontextor:
def __init__(self,name,mode):
self.name = name
self.mode = mode
def __enter__(self):
print "Hi enter here!!"
self.filehander = open(self.name,self.mode)
return self.filehander
def __exit__(self,*para):
print "Hi exit here"
self.filehander.close()
with Diycontextor('py_ana.py','r') as f:
for i in f:
print i
Custom File Manager
Related interview questions:
class StarkConfig:
def __init__(self,num):
self.num = num
def run(self):
self()
def __call__(self, *args, **kwargs):
print(self.num)
class RoleConfig(StarkConfig):
def __call__(self, *args, **kwargs):
print(345)
def __getitem__(self, item):
return self.num[item]
v1 = RoleConfig('alex')
v2 = StarkConfig('太白金星')
# print(v1[1])
# print(v2[2])
v1.run()
-------
class UserInfo:
pass
class Department:
pass
class StarkConfig:
def __init__(self, num):
self.num = num
def changelist(self, request):
print(self.num, request)
def run(self):
self.changelist(999)
class RoleConfig(StarkConfig):
def changelist(self, request):
print(666, self.num)
class AdminSite:
def __init__(self):
self._registry = {}
def register(self, k, v):
self._registry[k] = v
site = AdminSite()
site.register(UserInfo, StarkConfig)
# 1
# obj = site._registry[UserInfo]()
# 2
obj = site._registry[UserInfo](100)
obj.run()
-------
class UserInfo:
pass
class Department:
pass
class StarkConfig:
def __init__(self,num):
self.num = num
def changelist(self,request):
print(self.num,request)
def run(self):
self.changelist(999)
class RoleConfig(StarkConfig):
def changelist(self,request):
print(666,self.num)
class AdminSite:
def __init__(self):
self._registry = {}
def register(self,k,v):
self._registry[k] = v(k)
site = AdminSite()
site.register(UserInfo,StarkConfig)
site.register(Department,RoleConfig)
for k,row in site._registry.items():
row.run()
-------
class A:
list_display = []
def get_list(self):
self.list_display.insert(0,33)
return self.list_display
s1 = A()
print(s1.get_list())
-------
class A:
list_display = [1, 2, 3]
def __init__(self):
self.list_display = []
def get_list(self):
self.list_display.insert(0, 33)
return self.list_display
s1 = A()
print(s1.get_list())
------
class A:
list_display = []
def get_list(self):
self.list_display.insert(0,33)
return self.list_display
class B(A):
list_display = [11,22]
s1 = A()
s2 = B()
print(s1.get_list())
print(s2.get_list())