高度な構文

9173 ワード

高次関数:他の関数をパラメータまたは戻り値とする関数.JSと同様にpythonは高次関数を一部内蔵しています
  #      :map/reduce,           python
  #  map:                            
  #  [f(1), f(2), f(3), f(4), f(5)]
  def f1(x): return x*x
  print map(f1, [1, 2, 3, 4, 5])
  #    :[1, 4, 9, 16, 25]

  #  reduce:                         ,
  #                     
  #  f(f(f(f(1, 2), 3), 4), 5)
  def f2(x, y):  return x + y
  print reduce(f2, [1, 2, 3, 4, 5])
  #    :15

  #  filter:                    
  #  [f(1) ? 1 : None, f(2) ? 2 : None, f(3) ? 3 : None]
  def f3(x): return x%2 == 0
  print filter(f3, [1, 2, 3, 4, 5])
  #    :[2, 4]

  #  sorted:             ,            ,
  #  former < back   -1,former == back   0,former > back   1。
  #           ,           
  def f4(f, b):
    if(f < b):  return 1
    elif(f == b): return 0
    elif(f > b):  return -1
  print sorted([4, 3, 5, 1, 2])
  print sorted(f4, [4, 3, 5, 1, 2])
  #    :[1, 2, 3, 4, 5]
  #       [5, 4, 3, 2, 1]

匿名関数:pythonの匿名関数をキーワードlambdaで記述する
  #  lambda [params]: [return]
  lambda x: x*x #   :def f(x): return x*x

装飾モード:pythonの装飾モードは装飾関数によって実現されます
  def decorator(func):
    def wrapper(*args, **kw):
      #            
      ret = func(*args, **kw)
      #            
      return ret
    return wrapper

  @decorator
  def f(x, y, z):
    return x + y + z
  #    ,  f      decorator   

  #             :f = log(f)   ,     f           log    

  #        __name__       ,      log   
  import time
  def log(func):
    def wrapper(*args, **kw):
      tTime = time.time()
      print "function %s"%func.__name__,"has been called at %d."%tTime
      ret = func(*args, **kw)
      print "function %s"%func.__name__,"used %d"%(time.time() - tTime),"milliseconds"
      return ret
    return wrapper

  @log
  def f(x, y):  return x + y

  print f(1, 4)
  #    :function f has been called at 1502204876.
  #       function f used 0 seconds
  #       5

バイアス関数:私の理解は既存の関数に基づいて、一定の修正を行います(でも後で高次関数で簡単にできました--)
  #        
  import functools
  int2 = functools.partial(int, base=2)
  int2('1000000')

  #            (         )
  def f(x = 2): return x*x
  f3 = lambda x = 3: f(x)
  print f3()

モジュール:1つ.pyファイルはモジュールで、名前の衝突を防ぐために、モジュールを異なるパッケージに入れることができます:initがあります.pyファイルのフォルダはパッケージです
  root  #root 
    |
    +-- __init__.py
    |
    +-- abc.py  #root.abc  
    |
    +-- hello  #hello 
          |
          +-- __init__.py
          |
          +-- abc.py  #hello.abc  

インポートモジュール:指定したモジュールをimportキーワードでインポートする
  import module  # module             
  #        ,   ImportError  

  #       as            
  import module [as mdl]  #       mdl    

モジュールコンポーネントの役割ドメイン:関数、変数の公開、プライベートの使用を指定します.
  #   __XXXX__:    
  #  _XXXX or __XXXX:    
  #  XXXX:    

外部パッケージのインストール:npmと同じで、pipを使うだけです
  pip install package
  
  #             import      ,
  #  python         sys.path(  )         
  import sys
  print sys.path
  
  #       ,      sys.path  (  )
  #           (  )
  #  (          -_-)

≪新規プロパティの使用|Use New Properties|emdw≫:futureモジュールを導入すると、最新の構文クラスとオブジェクトを使用できます.
  #       (           ):
  class Test(superClass):
    pass

  #        、     
  class Test(object):
    def __init__(self, id, name):
      self.id = id
      self.name = name
    def printSelf(self):
      print self.id
      print self.name

  #        (   new   )
  a = Test(100, "abcd")
  a.printSelf()

すべてのpythonクラスのメソッドで、最初のパラメータはselfです.つまり、このクラスの現在のインスタンスです.
クラスメンバーアクセスドメイン:プライベートと公開のみに分けられ、プライベートメンバーの名前の前に二重下線が引かれます.
  class Test(object):
    def __init__(self, id):
      self.__id = id
    def __addId(self):
      self.__id = self.__id + 1
    def printId(self):
      self.__addId()
      print self.__id

  Test(10).printId()

継承とマルチステート:マルチステートは主にisinstance()関数に反映され、サブクラスオブジェクトが親クラスのインスタンスかどうかを尋ねると、Trueオブジェクト情報関数が返されます.
  #  type()             ,      ,python                   type  
  #     typeof
  import types
  print type(123) == type("abc")
  print type(123) == types.IntType
  #  type          ,        type       
  Hello = type('Hello', (object,), dict(hello=fn))
  #        :
  #    1、  
  #    2、     (  tuple,    ,)
  #    3、    KV 
  #        Hello        
  h = Hello()
 
  #  isinstance()                   
  print isinstance("abcd", str)

  #  dir()                  
  print dir(0)
  #    getattr()、setattr() hasattr()          
  #     JS obj[attr]、obj[attr] attr in obj

pythonで_XXXX__名前付き属性とメソッドは特殊な属性とメソッドとして識別され、前のfunctionクラスの_name__属性は特殊な属性です
動的メンバーの追加:
  #       ,python                 
  from types import MethodType
  a = Test(1)
  a.__age = 15
  a.setAge = MethodType(setAge, a, Test)
  
  #         ,             
  b = Test(5)
  b.setAge(12) #  Error

  #                      ,            

  #            ,    __slots__
  class Test(object):
    __slots__ = ("id", "name")

  Test().age = 10 #  Error

slotsは現在のクラスにのみ有効であり、そのサブクラスは影響を受けません(slotsプロパティは現在のクラスに属します)
詳細プロパティ:@property:アクセラレータと同様に、クラスのプロパティ(メンバー変数)へのアクセス方法と設定方法を追加します.
  class Student(object):
    def __init__(self, id):
      self.__id = id
      self.__name = ""
    @property
    def id(self):
      return self.__id
    @property
    def name(self):
      return self.__name
    @name.setter
    def name(self, name):
      if len(name) != 0:
        self.__name = name

多重継承:pythonは多重継承をサポートします(菱形の問題をどう処理すればいいか分かりません?)特殊な属性と方法:
  #  __str__           (   JS toString)
  #  __iter__          ,  for    
  #  __getitem__               (   C++   []   )
  #  __getattr__        (   JS obj[prop])
  #  __call__                     ,      
  std = Student(10)
  std()  #         std.__call__  

例外処理:基本的なtry-except(catch)-finally-raise(throw)は、条件式はTrueであるべきだと断言します.そうしないと、後のコードがエラーになります.
  assert n != 0, 'n is zero!'

ログ記録:import loggingパッケージの後、ログを記録できます.レベルを設定してログのタイプを指定できます
  import logging
  logging.basicConfig(level=logging.INFO)
  ...
  logging.info('n = %d' % n)
  ...

単一ステップデバッグツールpdb:コマンドラインレベルの単一ステップツール
  python -m pdb helloWorld.py
  #  l -         
  #  p -        
  #  n -          
  #            ,             pdb.set_trace()  (pdb import )

この方法で独自のIDEを作成したり、Sublime上でデバッグ環境を開発したりすることができます.
ユニットテストパッケージ:import unittestパッケージの後、ユニットテストクラスを定義できます.unittestからTestCaseから派生し、デフォルトでは【test】で始まるメソッドがテストメソッドとして識別され、テストユニットの実行時に自動的に実行される
import unittest
class Animal:
    def __init__(self):
        self.__health = 10
        self.__body = { "body": 1, "head": 1, "hands": 2, "foot": 2 }
    def eat(self, food):
        self.__health  += food
    def printState(self):
        print "Current health",self.__health
    @property
    def health(self):
        return self.__health
    def __getattr__(self, key):
        return self.__body[key]

class TestAnimal(unittest.TestCase):
    def testInit(self):
        a = Animal()
        self.assertEquals(a.health, 10)
    def testPrint(self):
        a = Animal()
        self.assertTrue("printState" in a)
    def testEat(self):
        a = Animal()
        with self.assertRaises(KeyError):
            val = a["tail"]

    #              
    def setUp(self):
        print "Start test"
    #              
    def tearDown(self):
        print "Test end"

if __name__ == '__main__':
    unittest.main()

ドキュメントテスト:テスト用のコードをドキュメントに書き、コマンドラインで実行できます.コンパイラは、ドキュメント内のテストコードを実行し、結果をドキュメントに書き、ドキュメントの使用例を生成します.
  #             
  class Dict(dict):
    '''
    Simple dict but also support access as x.y style.

    >>> d1 = Dict()
    >>> d1['x'] = 100
    >>> d1.x
    100
    >>> d1.y = 200
    >>> d1['y']
    200
    >>> d2 = Dict(a=1, b=2, c='3')
    >>> d2.c
    '3'
    >>> d2['empty']
    Traceback (most recent call last):
        ...
    KeyError: 'empty'
    >>> d2.empty
    Traceback (most recent call last):
        ...
    AttributeError: 'Dict' object has no attribute 'empty'
    '''
    def __init__(self, **kw):
        super(Dict, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

  if __name__=='__main__':
    import doctest
    doctest.testmod()

最後の2行のコードに気づきました.モジュールが正常にインポートされるとdoctestは実行されません.doctestは、コマンドラインが実行されている場合にのみ実行されます.したがって、doctestが非テスト環境で実行される心配はありません.