Object behavior and special methods in Python (1) object creation and destruction, and python destruction

Source: Internet
Author: User

Object behavior and special methods in Python (1) object creation and destruction, and python destruction

In Python, the class calls the _ new _ () class method to create an instance, and calls the _ init _ () method to initialize the object, to destroy an object, call the _ del _ () method.

The first parameter of the _ new _ () method is cls. Usually, an instance of cls is returned, and the _ init _ () of the new instance is returned __() the method will be similar to _ init _ (self [,...]) self is a new instance. Other parameters are the same as those passed to _ new.

If the _ new _ () method does not return the cls instance, _ init _ () will not be called.

For a class:

class Foo(object):    def __init__(self, name):        self.name = namef = Foo('bar')

When performing the f = Foo ('bar') operation, perform the following steps to create and initialize an instance:

f = Foo.__new__(Foo, 'bar')if isinstance(f, Foo):    Foo.__init__(f, 'bar')
_ New _ (cls [,...])

The _ new _ () method is a static class method that takes the instance class as the first parameter. Other parameters are the parameters passed to the object construction expression, which are the same as those passed to _ init.

Generally, super (currentclass, cls) is used ). _ new _ (cls [,...]) to call the _ new _ () method of the superclass to create a new instance of the class.

When you define an object, the _ new _ () method is rarely defined. If it is defined, it is generally used to define the Meta class or some objects that inherit the self-Immutable built-in data types (integers, strings, tuples, etc.

When defining immutable data types, the object cannot be modified in _ init _ () because the object is immutable, the _ new _ () method is executed before the instance is created:

class Upperstr(str):    def __new__(cls, value=''):        return str.__new__(cls, value.upper())

The string instances created by the Upperstr class are in uppercase:

>>> u = Upperstr('hello world')>>> u'HELLO WORLD'

You can also use the _ new _ () method in singleton mode to create a unique instance and put it in a class variable. This instance will be returned each time you create the instance:

class Singleton(object):    def __new__(cls, *args, **kwargs):        if not hasattr(cls, '_inst'):            cls._inst=super(Singleton, cls).__new__(cls, *args, **kwargs)        return cls._inst
_ Init _ (self [,...])

The _ init _ () method is used to initialize the object attributes and is called when the instance is created. The parameter is the parameters passed to the class constructor expression. If the base class has the _ init _ () method, the _ init _ () method of the inherited class must be explicitly called: BaseClass. _ init _ (self, [args...]).

A special restriction of the constructor is that no value can be returned. This will cause a TypeError to be thrown during the runtime.

The _ init _ () method generally contains a large number of values for self. attr = attr:

class Foo(object):    def __init__(self, name, color, num=1):        self.name = name        self.color = color        self.num = numf = Foo('bar', 'yellow')

If you do not want to repeat the assignment operation, you can do the following:

class Foo(object):    def __init__(self, name, color, num=1):        print locals()f = Foo('bar', 'yellow')

The local namespace of the _ init _ () method is as follows:

{'color': 'yellow', 'self': <__main__.Foo object at 0x00000000055C4780>, 'num': 1, 'name': 'bar'}

The self variable is the created instance, and the other variables name, color, and num to be assigned to the instance are all in the variable. The instance attribute is stored in the _ dict _ variable of the instance. You only need to put the variables to be assigned values into _ dict:

class Foo(object):    def __init__(self, name, color, num=1):        self.__dict__.update(locals())        del self.__dict__['self']
>>> f = Foo('bar', 'yellow')>>> f.name'bar'>>> f.color'yellow'>>> f.num1

In this way, when there are many instance attributes, it will be much simpler. However, when a feature or descriptor is used to wrap an object's attributes, a problem occurs because the properties or descriptor encapsulated attributes are not stored in _ dict, the solution is to use setattr built-in functions:

def attr_from_locals(locals_dict):    self = locals_dict.pop('self')    for k,v in locals_dict.items():        setattr(self, k, v)        class Foo(object):    def __init__(self, name, color, num=1):        attr_from_locals(locals())

If the _ init _ () method uses some local variables that do not need to be assigned to the instance, then locals () will contain these local variables, we can accurately pass the parameters in _ init.

F. the _ code _ attribute obtains the function's bytecode Object c, and the bytecode object's attribute c. co_varnames can get the tuples of the local variable name (function parameters are prior, and local variables in the function are behind), c. co_argcount can be used to obtain the number of function location parameters, and the slice can be used to remove local variables in the function:

def attr_from_locals(locals_dict):    self = locals_dict.pop('self')    code = self.__init__.__func__.__code__    args = code.co_varnames[1:code.co_argcount]    for k in args:        setattr(self, k, locals_dict[k])        class Foo(object):    def __init__(self, name, color, num=1):        x = 1        attr_from_locals(locals())f = Foo('bar', 'yellow')

We can see that the x variable is not assigned to the instance:

>>> f.name'bar'>>> f.color'yellow'>>> f.num1>>> f.xTraceback (most recent call last):  File "<pyshell#87>", line 1, in <module>    f.xAttributeError: 'Foo' object has no attribute 'x'
_ Del _ (self)

When the instance is to be destroyed, the _ del _ () method of the object is called. Note that when statements such as del a are used, the _ del _ () method is not called, but a reference count is reduced. When the reference count of an object is reduced to 0, to call _ del __().

The _ del _ () method is rarely required. Instances defining this method cannot be collected by python's garbage collector.

When you need to clear the file, close the network connection, and so on, you can define a close () method to explicitly execute the close operation.

 

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.