wtysos11 / blogWiki

Use to store public paper and organize them.
17 stars 4 forks source link

读懂python之常见语法糖 #157

Open wtysos11 opened 3 years ago

wtysos11 commented 3 years ago

python的代码可能并不复杂,但是其中的语法特性是真的挺多的。

  1. __call__方法

需要注意: google开源规范 比较需要留意的是注释,开源库的注释还是比较统一的。

函数和方法:

  1. Args:列出每个参数的名字,并在名字后面使用一个冒号和空格,分割对该参数的描述。描述包括所需的类型和含义
  2. Returns:(或者yield,用于生成器)描述返回值的类型和语义,如果函数返回None,则可忽略
  3. Raise:列出与接口有关的所有异常 例子:

    def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.
    
    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.
    
    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.
    
    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:
    
        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}
    
        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.
    
    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass

    类: 类应该在其定义下有一个描述该类的文档字符串。 如果类有公共属性,那么文档中应该有一个属性段,并遵守和函数参数相同的格式。

    class SampleClass(object):
    """Summary of class here.
    
    Longer class information....
    Longer class information....
    
    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """
    
    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0
    
    def public_method(self):
        """Performs operation blah."""
wtysos11 commented 3 years ago

类中的initcall函数

参考 init即构造函数,call可以让类如函数一样调用。其中call又被成为魔法方法。

例如:

bar = Bar() # 调用__init__方法
bar() # 调用__call__方法

call方法可以用作实现类装饰器,ref