A reflection
The concept is reflected by Smith in 1982 first proposed, mainly 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)
Foo class:
F = 'static class variable'
DEF the init (Self, name, Age):
the self.name name =
self.age = Age
def say_hi(self):
print('hi,%s'%self.name)
obj=Foo('egon',73)
Detecting whether a property is containing
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))
Acquiring property
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()
print (getattr (obj, 'aaaaaaaa', 'does not exist ah')) given #
Setting Properties
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))
Delete property
delattr (obj, 'Age')
delattr (obj, 'SHOW_NAME')
delattr (obj, 'show_name111') # does not exist, an error
print(obj.__dict__)
Example instantiation object
reflector to the object
class Foo(object):
staticField = "old boy"
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
@staticmethod
def bar():
return 'bar'
getattr Print (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]
the hasattr (THIS_MODULE, 'S1')
getattr (THIS_MODULE, 'S2')
reflected current module
A code module
Test DEF ():
Print ( 'from The Test')
"" "
Program Category:
module_test.py
index.py
Current file:
index.py
"" "
Another code module
import module_test as obj
obj.test()
print(hasattr(obj,'test'))
getattr(obj,'test')()
Examples of other modules
reflect 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.
the User class:
DEF the Login (Self):
Print ( 'Welcome to the login page')
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
the User class:
DEF the Login (Self):
Print ( 'Welcome to the login page')
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
View Code
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()
In fact, as a function of static methods
print(isinstance(A.func2,FunctionType)) # True
print(isinstance(obj.func2,FunctionType)) # True
View Code
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, 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: the init
1.3 only
class B:
def len(self):
print(666)
B = B ()
len (B) # an object len __len__ triggered method.
class A:
def init(self):
self.a = 1
self.b = 2
def __len__(self):
return len(self.__dict__)
a = A()
print(len(a))
View Code
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))
View Code
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)
View Code
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)
View Code
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 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 () # performs the init
obj () # perform Call
View Code
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)
View Code
3.07 of
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 It 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)
View Code
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 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, we 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 it 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), 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
Singleton specific analysis
singleton specific analysis
duplicated code
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__)
View Code
3.10 related context manager
enter exit
If you want to target a class of operations carried out with as not.
class A:
def init(self, text):
self.text = text
with A ( 'uncle') AS F1:
Print (f1.text)
not so they can not operate
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 ( 'uncle') AS F1:
Print (f1.text)
Print (f1.text)
have such that they can operate
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()
Diycontextor with ( 'py_ana.py', 'R & lt') 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]
RoleConfig = V1 ( "Alex")
V2 = StarkConfig ( 'Taibaijinxing')
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._registryUserInfo
2
obj = site._registryUserInfo
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())
View Code