Python new class Singleton pattern and scope (iv)

Source: Internet
Author: User
Tags instance method

1 new class and old class

The new class has all the characteristics of the classic class, and there are a number of features, such as __init__ changes, new static methods __new__ , Python3 are now using new classes, the new class is breadth first, the old class is depth first

#新式类class C(object):    pass#经典类class B:    pass
(1) Built-in object objects
1. __new__,__init__方法这两个方法是用来创建object的子类对象,静态方法__new__()用来创建类的实例,然后再调用__init__2__delattr____getattribute__3__hash____repr__, __str__方法print(someobj)会调用someobj.__str__(), 如果__str__没有定义,则会调用someobj.__repr____str__()和__repr__()的区别:默认的实现是没有任何作用的__repr__的目标是对象信息唯一性__str__的目标是对象信息的可读性容器对象的__str__一般使用的是对象元素的__repr__如果重新定义了__repr__,而没有定义__str__,则默认调用__str__时,调用的是__repr__也就是说好的编程习惯是每一个类都需要重写一个__repr__方法,用于提供对象的可读信息,而重写__str__方法是可选的。实现__str__方法,一般是需要更加好看的打印效果,比如你要制作一个报表的时候等。
(2) Methods of the class

Static methods

Class method

也是可以通过类和它的实例进行调用,不过它是有默认第一个参数,叫做是类对象,一般被命名为cls,当然你也可以命名为其它名字,这样就你可以调用类对象的一些操作,代码如下,使用装饰符@classmethod创建:

New Class (New-style-class)

__init__方法: Initialization method of a class

__new__Static methods

The new class has a __new__ static method, and its prototype isobject.__new__(cls[, ...])

The CLS is a class object, and when you call C(*args, **kargs) to create an instance of Class C, the internal invocation of Python is

C.__new__(C, *args, **kargs), and then the return value is instance C of Class C, in the confirmation

C is an instance of C, and Python calls again C.__init__(c, *args, **kargs) to initialize instance C.

So call an instance c = C (2) and actually execute the code as:

C=C.__new__C2)if isinstance(c, C): C.__init__C at)#__init__第一个参数要为实例对象    classSingleton (Object): _singletons={}def __new__(CLS):if  notCls._singletons.has_key (CLS):#若还没有任何实例CLS._SINGLETONS[CLS]= Object.__new__(CLS)#生成一个实例        returnCLS._SINGLETONS[CLS]#返回这个实例A=Singleton () b=Singleton ()ID(a)#35966666    ID(b)#35966666 #注: Singleton mode, two instances pointing to the same memory address
(3) New class instances

Instances of modern classes also have new features. For example, it has a property function, which affects how properties are accessed, and __slots__ new properties that affect the generation of subclass instances, and a new method __getattribute__, which is more generic than the original __getattr__.

__slots__Property

Typically, every instance of X has a __dict__ property that records all the properties and methods in the instance, and also through this dictionary,

You can bind an instance to arbitrary properties. The __slots__ function of a property is that when Class C has fewer variables and has __slots__ properties,

An instance of Class C has no __dict__ attributes, but a fixed place for the value of the variable. If you try to access a __slots__

attribute, the instance will be given an error. What is the benefit of doing so? __slots__property, although the instance loses the convenience of binding any property,

However, because each instance has no __dict__ attributes, it can effectively save the memory consumption of each instance, which is helpful to generate small and fine

Example of a dry case.

Defining __slots__ Properties

classAObject):def __init__( Self): Self. x= 1         Self. Y= 2__slots__=(' x ',' y ') A=A () a.z= 3A.u= 4  #都会报错, you cannot add a property to an instance, and the __dict__ dictionary set has no changeclassAObject):def __init__( Self): Self. x= 1         Self. Y= 2A=A () a.x= 3  #不会报错, add the ' X ' attribute to the __dict__ dictionary assembly

Some points to be aware of when using __slots__:

1.  2. 如果定义了__slots__属性,还是想在之后添加新的变量,就需要把‘__dict__‘字符串添加到__slots__的元组里。3. 定义了__slots__属性,还会消失的一个属性是__weakref__,这样就不支持实例的weak reference,如果还是想用这个功能,同样,可以把‘__weakref__‘字符串添加到元组里。4. __slots__功能是通过descriptor实现的,会为每一个变量创建一个descriptor。5. __slots__的功能只影响定义它的类,因此,子类需要重新定义__slots__才能有它的功能。
__getattribute__方法

For instances of modern classes, access to all properties and methods is done through __GETATTRIBUTE__, which is implemented by the object base class. If there is a special requirement, you can overload the __getattribute__ method.

2 __init__ with the __new__ difference
    1. __new__is a static method, but __init__ an instance method.
    2. __new__method returns a created instance, and nothing is __init__ returned.
    3. Only __new__ after the instance of a CLS is returned __init__ can it be called.
    4. Called when a new instance is created __new__ , when an instance is initialized __init__ .

__metaclass__is when the class is created. So we can use __metaclass__ them separately, __new__ and __init__ do something about class creation, instance creation, and instance initialization.

3 single-Case mode

? Singleton mode is a kind of common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed, so as to facilitate the control of the number of instances and save system resources, there are several instances of the class in the system, which can seriously waste memory resources if you want to have only one object in a class in the system, A singleton mode is the best solution.

__new__()__init__()is called before to build the instance object. Using this method and the properties of the class can realize the design pattern of the singleton mode. Singleton mode refers to the creation of unique objects, and the singleton pattern design class can only be instantiated once

In general Python, you can use the following methods to implement a singleton pattern

    • Using modules (Import imports)
    • Use__new__
    • Using adorners (decorator)
    • Using meta-classes (Metaclass)

(1) How to use __new__

class Singleton(object):    def__new__***kw):        ifnothasattr‘_instance‘#如果该类是否含有实例            =super(Singleton, cls)            = orig.__new__***kw)        return cls._instanceclass MyClass(Singleton):    =1#如果 cls._instance 为 None 则创建实例,否则直接返回 cls._instance。

(2) Shared attributes (using Metaclass)

A meta-class (Metaclass) can control the creation of a class, and it mainly does three things:

    • Block creation of classes
    • Modifying the definition of a class
    • Returns the Modified class

When you create an instance, you point all instances to the __dict__ same dictionary, so that they have the same properties and methods.

class Borg(object):    = {}    def__new__***kw):        =super(Borg, cls).__new__***kw)        = cls._state        return obclass MyClass2(Borg):    =1

(3) Decorator version

def singleton(cls):    = {}    def getinstance(***kw):        ifnotin instances:            = cls(***kw)        return instances[cls]    return getinstance@singletonclass MyClass:  ...

(4) Import method (using module)

As a Python module, it's a natural, single-case pattern.

# mysingleton.pyclass My_Singleton(object):    def foo(self):        pass= My_Singleton()# to usefromimport#将类进行导入使用my_singleton.foo()
4 python Scopes

Python's scope is global and local , and the scope of the Python variable is divided into the following four categories:

L (local) local scope
In functions outside of the E (enclosing) closure function
G (Global) scope
B (built-in) built-in scopes

(1) Local scope

Understand the concept of the next block-level scope before you understand the local scope

 #块级作用域   If  1  ==  1 : Name =
       "LOL"  print  (name) for  I in  range  (10 ): Age =  iprint  (age) # Output:  c:/ users/ l/ pycharmprojects< Span class= "OP" >/ s14/ preview/ day8/  scope / test.pylol9   

You can see that Python code is running OK, why external variables can be called internally? Because there is no concept of block-level scope in Python, the variables in the code block can be called externally, so it can be run successfully, that is, a similar conditional judgment (If.....else), a looping statement (for x in data), an exception snap (Try ... Catch) Variables such as these can be used globally. However, it is not possible to distinguish scopes clearly, so Python introduces local scopes

#局部作用域def  func():    ="lol"func()  #调用函数print(name)#输出Traceback (most recent call last):  "C:/Users/L/PycharmProjects/s14/preview/Day8/作用域/test.py"23in<module>    print(name)NameError‘name‘isnot defined

Even if a function is executed, the scope of name is only inside the function, the outside still cannot be called, so the function can produce local scope, in Python module, class, function (Def, lambda) will produce a new scope.

(2) Scope chain

#作用域链="张三"def func1():    ="李四"    def func2():        ="王五"        print(name)    func2()func1()#输出"王五"

Func1 () invokes a function to perform a variable assignment operation, and when Func2 () is called, the Name property in print is first searched from the local scope, from inside to outside, of course the ' Harry ' is the first to be found. Python has a scope chain, the variables will be from the inside out to find, first go to their own scope to find, they did not go to the superiors to find, until the error can not be found.

(3) global scope and built-in scope

=int(2.9)  # 内建作用域=0  # 全局作用域def outer():    =1  # 闭包函数外的函数中    def inner():        =2  # 局部作用域

(4) Global keyword

A global variable refers to a variable outside the function, which can be used globally, a local variable is a variable defined within a function, and can only be declared within a function using the Global keyword if you want to modify the external scope of the variable inside the scope.

=100def demo():    global a    =123    print(a)demo()print(a)#运行结果是123123

The result should be 123,100, but since global declaration A is a global scope, a points to 123 after the assignment is performed, so two times it prints 123.

Summary below:

? In Python, the scope of a variable is always determined by where the value is assigned in the code. When Python encounters a variable, he searches in this order: local scope (native) → current scope embedded local scope (enclosing locals) → Global/module scope (global) → Built-in scope (built-in)

Python new class Singleton pattern and scope (iv)

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.