Python Cookbook Third Edition study note 13: Classes and Objects (v) proxy classes and memory reclamation

Source: Internet
Author: User

Proxy class:
The role of the proxy class actually has a similar inheritance, if you want to have an instance of the property Access Proxy to another internal instance, you can use inheritance can also use the proxy. Consider the application of the agent:
A:
Spam (Self,x):
% x
Foo (self):
print ' in Class a:foo () '
B1:
__init__ (self):
Self._a=a () ⑴
Spam (Self,x):
Self._a.spam (x) ⑵
Foo (self):
Self._a.foo () ⑶
Bar (self):
Pass
"__main__":
B=B1 ()
B.spam (42)
B.foo ()
E:\python2.7.11\python.exe e:/py_prj/python_cookbook/chapter8.py
In Class A x=42
In Class A:foo ()
In (1), assign the self._a to an instance of a. In (2), Self._a.spam (x), Self._a.foo is actually equal to a (). spam (x) and A (). Foo (). In this way, the implementation in a is accessible in B1. This also implements the agent for spam () and foo ()
If only two functions need proxy, then the amount of code is not very large, but if there are many functions need to proxy, each function in B1 need to write a corresponding agent function is very troublesome. The use of __getattr__ in this case is much easier
A:
Spam (Self,x):
% x
Foo (self):
print ' in Class a:foo () '

B:
__init__ (self):
Self._a=a ()
Bar (self):
Pass
__GETATTR__ (self, item):
GetAttr (Self._a,item)
"__main__":
B=b ()
B.spam (42)
B.foo ()
E:\python2.7.11\python.exe e:/py_prj/python_cookbook/chapter8.py
{' name ': ' X '}
In Class A x=42
In Class A:foo ()
__GETATTR__ is called when the corresponding attribute is not found in the instance and in the class. The above implementation will call __getattr__ when calling B.spam (42) and B.foo (). GetAttr (Self._a,item) is equivalent to Self._a.item
Creates an instance that does not call the Init method. The __init__ method in Python is actually a constructor that calls the __init__ method first when the corresponding class instance is called. But is there a way to bypass execution __init__? __NEW__ can achieve this goal, see the following example.
Date (object):
__init__ (Self,year,month,day):
Self.year=year
Self.month=month
Self.day=day

"__main__":
d=date.__new__ (Date)
D.year
E:\python2.7.11\python.exe e:/py_prj/python_cookbook/chapter8.py
Traceback (most recent):
File "e:/py_prj/python_cookbook/chapter8.py", line 236, in <module>
Print D.year
Attributeerror: ' Date ' object has no attribute ' year '
First, an instance is created by date.__new__ (Date), and when the d.year is executed, there is no year attribute, because __init__ is not executed. If you add the following code, there is no problem.
D.__init__ (a)
D.year
Attention:
Only in the new class will there be __new__ methods that are not in the classic class, so to use the __new__ method in python2.7, you must inherit from object. And the python3.0 are all new classes. You can use __new__ directly
We can also write this __new__ to the class:
Date (object):
__init__ (Self,year,month,day):
Self.year=year
Self.month=month
Self.day=day
__new__ (CLS, *args, **kwargs):
print ' new '
Object.__new__ (Cls,*args, **kwargs)
object.__new__ (Cls,*args, **kwargs)
"__main__":
D=date (2017,7,16)
E:\python2.7.11\python.exe e:/py_prj/python_cookbook/chapter8.py
New
<__main__. Date Object at 0x017dd3d0>
Through the above implementation can see __new__ actually feedback is the self in the __init__. The __new__ method is better than the __init__ method during the instance creation process. In addition, the return value must be returned in __new__, which is the generated instance. So __new__ and __init__ are like such a relationship, __INIT__ provides the raw material for production self (but does not guarantee that this raw material source is authentic, like above it uses another unrelated class __new__ method class to get this instance), and __init__ uses __ NEW__ gives the raw material to refine this object (though it does not know whether these ingredients are authentic)
If we do not want to initialize the instance with __init__ at all, we can use the following method:
Date (object):
@classmethod
Today (Cls,year,month,day):
D=CLS.__NEW__ (CLS)
d.year=2017
D.month=7
D.day=16
D

"__main__":
D=date.today (2017,7,16)
D.year
By Classmethod The Today method, you can also implement the __init__ method by calling the Today method
Garbage Memory Recycling
One: Garbage Memory recovery:
Internally, when an object is created, Python always holds an integer in the object's C struct, called the reference number . At the beginning of the period, Python sets this value to 1: When the reference number is 0, the object is destroyed and the memory is freed

Case that causes reference count +1:

    1. Objects are created, such as N=1
    2. object is referenced, such as N1=n
    3. The object is passed into a function as a parameter, for example, func (n)
    4. Object as an element, stored in a container, such as LIST1=[N,N1]

Case that causes reference count-1

    1. The alias of the object is explicitly destroyed, for example del a
    2. The alias of the object is assigned a new object, such as a=2
    3. An object leaves its scope, such as the local variable in the Func function when the F function finishes executing (global variable does not)
    4. The container where the object resides is destroyed, or the object is deleted from the container

Refer to the following code:

Node (object):
__init__ (Self,val):
Self.value=val
"__main__":
N1=node (' abc ')
N2=node (' def ')
N3=node (' Ghi ')
Sys.getrefcount (N1)
Sys.getrefcount (N2)
Sys.getrefcount (N3)

E:\python2.7.11\python.exe e:/py_prj/python_cookbook/chapter8.py

2

2

2

Since n1,n2,n3 are passed into the Getrefcount, the final reference count is 2, according to the rules that are counted above. The corresponding relationship is as follows.

If you change the reference, let N2 refer to N1.n2=n1. " Ghi "is referenced at the same time by N1 and N2, so the reference number becomes 2. The reference count is 0 and the memory is emptied because there is no reference to ABC.

Python Cookbook Third Edition study note 13: Classes and Objects (v) proxy classes and memory reclamation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.