[Python] --- cow-off (Green League)

. 1, [I I I in Range for (10)] and (I I I in Range for (10)) the difference between
a formula is a list, a type iterator


# 列表解析生成列表
>>> [i*i for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> a = [i*i for i in range(10)]
>>> type(a)
<class 'list'>

# 生成器表达式
>>> b = (i*i for i in range(10))
>>> b
<generator object <genexpr> at 0x102b11620>
>>> type(b)
<class 'generator'>

>>> # 两者之间转换
>>> list(b)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Refer to: https: //blog.csdn.net/qq_34358193/article/details/102911407, record type generators and iterators.

2, new new () and __init __ () distinction, who should perform

_ New new _ () method for the new class is a class in emerging it in the constructor (_ the init call before _ ()).

__new__()的声明

def __new__(cls, *args, **kwargs):
    pass

_ New new _ () parameters and __init __ () the same, but _ the init _ () is called after the class instance creation, and _ new new _ () method is the method to create a class instance. _ The init _ () has a parameter self, self is __new __ () returns instance, _ the init _ () perform some other action based on the initialization __new __ () on, _ the init _ () no return value.

class Foo(object):
    def __init__(self):
        print '__init__'

    def __new__(cls,*args,**kargs):
        print '__new__'
        return super(Foo,cls).__new__(cls,*args,**kargs)
f = Foo()
'''
__new__
__init__
'''

The code may prove __new __ before calling a method __init __ () ().

The implementation process is as follows

F = Foo ()
__new execution of Foo __ () method, _ new new _ () method returns Foo an instance of
execution __new __ () method returns an instance of __init __ () method
is apparent from the above, _ the init _ () and _ _new __ difference () are the following

_ The init _ () initialization process normally used to initialize a new instance of the control example, some attributes such as adding, to do some additional operations, occurs after completion of the class instance is created, it is an instance method of class

_ New new _ () commonly used to control generating a new instance of a class-level method which
may utilize __new __ () Example single-mode

#!/usr/bin/python
# -*- coding: utf-8 -*-
class Singleton(object):
    '''单例模式'''
    def __init__(self):
        print '__init__'

    def __new__(cls,*args,**kargs):
        if not cls.__dict__.get('_Singleton__instance'):
            cls._Singleton__instance = super(Singleton,cls).__new__(cls,*args,**kargs)
        return cls._Singleton__instance

m = Singleton()
n = Singleton()
print m is n
'''
__init__
__init__
True
'''

new new () features

new new () method is called when the class is instantiated preparing itself;
new new static method () method is always kind, even if not coupled with a static method decorators;
Note

If there is no redefinition __new __ (), the Python default call parent class __new __ () method is configured according to the MRO order instance of the class, because the object is a base class for all classes in the new definition of the new class, you must be able to find __new __ () method;

If the new class overrides __new __ () method, you can choose a new class __new __ () method for producing instance;

(It must be a new class, the new class must __new __ (), because all are the descendants of the new class of object, and the classic category is not __new __ () method)

If __new __ () does not return the current instance of the class, the current class __init __ () method is not called;

If __new __ () Returns the other class (new class or Classic available) instance, it will call the constructor of that class to be returned;

That return Who instance, who is called __init __ () method does not return instance, it does not call the __init __ () method

class Foo1(object):
   def __init__(self, *args, **kwargs):
       print "Foo1 __init__"

   def __new__(cls, *args, **kwargs):
       return super(Foo1,cls).__new__(cls, *args, **kwargs)  

class Foo2(object):
   def __init__(self):
       print "Foo2 __init__"

   def __new__(cls, *args, **kwargs):
    '''返回Foo1的实例'''
    return Foo1()

class Foo3(object):
   def __init__(self):
       print "Foo3 __init__"

   def __new__(cls, *args, **kwargs):
    pass

foo1 = Foo1()      #Foo1 __init__
print type(foo1)   #<class '__main__.Foo1'>

foo2 = Foo2()      #Foo1 __init__,调用的是Foo1的__init__()方法
print type(foo2)   #<class '__main__.Foo1'>

foo3 = Foo3()
print type(foo3)   #<type 'NoneType'>

----------------
Disclaimer: This article is "small rabbit worry Sang" CSDN bloggers original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: HTTPS: //blog.csdn.net/lis_12/article/details/54631089
----------------
Reference link: https: //blog.csdn.net/lis_12 / article / details / 54631089

3, singleton

Singleton (Singleton Pattern) is a common software design pattern, the main purpose of this mode is to ensure that a certain class has only one instance exists . When you want in the whole system, can appear only one instance of a class, singleton objects can come in handy.

1, based on __new__ way to achieve (recommended, convenient)
When we achieve a single case, in order to ensure the security thread inside the lock needs to be added.
We know that when we instantiate an object, the method is to perform a __new__ class (we did not write the default call object._ new_ ), instantiate an object; then execute the __init__ method of the class of this object is initialized, all based on this we can achieve singleton pattern.

import threading
class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass


    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = object.__new__(cls)  
        return Singleton._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)

def task(arg):
    obj = Singleton()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()


#打印结果
<__main__.Singleton object at 0x038B33D0> <__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>

In this way single-mode embodiment, after the object instance, and usual methods instantiate the object as obj = Singleton ()
singleton pattern
in several ways singletons
1. Module
2. decorator
3. use class
4. implement (recommended to use, convenient) based __new__ method
5. based embodiment metaclass
knowledge
implemented singleton

Reproduced in: https: //www.cnblogs.com/huchong/p/8244279.html

4, the decorative implemented Singleton

def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton

@Singleton
class A(object):
    a = 1

    def __init__(self, x=0):
        self.x = x
    #定制类
    '''
    __str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。
    解决办法是再定义一个__repr__()。但是通常__str__()和__repr__()代码都是一样的,所以,有个偷懒的写法
    '''
    def __str__(self):
        return 'A object(x:%s)'%self.x

a1 = A(2)
a2 = A(3)
print(a1)
print(a2)

5, the sequence of the binary tree and deserialize

【topic】:

Binary file is recorded as a sequence of binary tree process is called reconstruction of the original binary file contents through a process called binary deserialization. A head fixed to the head node of the binary tree and binary node values ​​of known type 32-bit integer. Please design the serialization and deserialization of the binary tree scheme and implemented in code.

[Thinking]:

Method for the preorder traversal and two kinds of layers.

class TreeNode:
  def __init__(self, x):
    self.val = x
    self.left = None
    self.right = None
class Solution:
  def __init__(self):
    self.sIndex = 0

#序列化二叉树
#序遍历二叉树
  def recursionSerialize(self, root):
    series = ''
    if root == None:
      series += ',$'
    else:
      series += (',' + str(root.val))
      series += self.recursionSerialize(root.left)
      series += self.recursionSerialize(root.right)
    return series
  def Serialize(self, root):
    return self.recursionSerialize(root)[1:]
'''
结果
root = TreeNode(11)
root.left = TreeNode(2)
root.right = TreeNode(3)
series = Solution().Serialize(root)
print(series)
>>>11,2,$,$,3,$,$
'''

'''
反序列化
先构建根节点,然后左节点,右节点,同样是递归
注意由于使用的是字符串的表示形式,可以先转化为list,
print(series.split(','))
>>>['11', '2', '$', '$', '3', '$', '$']
'''
  def getValue(self, s, sIndex):  #处理超过10的数字,将数字字符转变为数字
    val = 0
    while ord(s[sIndex]) <= ord('9') and ord(s[sIndex]) >= ord('0'):
      val = val * 10 + int(s[sIndex])
      sIndex += 1
    return val, sIndex - 1

#下面是反序列化的递归函数:
  def Deserialize(self, s):
    if self.sIndex < len(s):
      if s[self.sIndex] == ',':
        self.sIndex += 1
      if s[self.sIndex] == '$':
        return None
      val, self.sIndex = self.getValue(s, self.sIndex)
      treeNode = TreeNode(val)
      self.sIndex += 1
      treeNode.left = self.Deserialize(s)
      self.sIndex += 1
      treeNode.right = self.Deserialize(s)
      return treeNode

Reprinted: https: //www.jb51.net/article/157217.htm

Published 35 original articles · won praise 10 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34358193/article/details/103170649