標籤:

Python built-in functions D&E

承接Python built-in functions C,繼續探索python的內置函數。

17~19 . delattr(object, name) setattr(object, name, value),getattr(object, name[, default])

delattr(object, name)

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object』s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, foobar) is equivalent to del x.foobar.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, foobar, 123) is equivalent to x.foobar = 123.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object』s attributes, the result is the value of that attribute. For example, getattr(x, foobar) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Python一切皆對象,這三種方法分別可以實現對屬性的刪除,創建,獲取。

  • getattr(x,name)-->x.name
  • setattr(x,name,value)--> x.name=value
  • delattr(x,name)--> del x.name

20. dict

  • class dict(**kwarg)
  • class dict(mapping, **kwarg)
  • class dict(iterable, **kwarg)

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

字典是python基本的數據類型之一,上述是幾種用來創建字典的方法。可以接收的參數包括鍵值對(A=B),mapping({A:B}),迭代對象(((A,B),(C,D)))。關於字典的基本方法,這裡就不再贅述了。

21. dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named dir(), this method will be called and must return the list of attributes. This allows objects that implement a custom getattr() orgetattribute() function to customize the way dir() reports their attributes.

If the object does not provide dir(), the function tries its best to gather information from the object』s dict attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom getattr().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

If the object is a module object, the list contains the names of the module』s attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object』s attributes』 names, the names of its class』s attributes, and recursively of the attributes of its class』s base classes. The resulting list is sorted alphabetically. For example:

>>> import struct>>> dir() # show the names in the module namespace[__builtins__, __doc__, __name__, struct]>>> dir(struct) # show the names in the struct module[Struct, __builtins__, __doc__, __file__, __name__, __package__, _clearcache, calcsize, error, pack, pack_into, unpack, unpack_from]>>> class Shape(object): def __dir__(self): return [area, perimeter, location]>>> s = Shape()>>> dir(s)[area, perimeter, location]Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

這個函數很常用,可以用來查看一個對象裡面有什麼函數和屬性。

  • 不傳入值時,返回當前層級的一些值,包括導入的庫
  • 當傳入模塊時,返回模塊里所有屬性的名稱
  • 當傳入類或類型時,返回類即其繼承的類的所有屬性名

22. divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

用來返回兩個數的商和餘數。

23 enumerate

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over

>>>> seasons = [Spring, Summer, Fall, Winter]>>> list(enumerate(seasons))[(0, Spring), (1, Summer), (2, Fall), (3, Winter)]>>> list(enumerate(seasons, start=1))[(1, Spring), (2, Summer), (3, Fall), (4, Winter)]

Equivalent to:

def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1

這個我們之前講過,就是以tuple形式返回序列的index和對應的value。是一個生成器。

24. eval(expression[, globals[, locals]])

The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks 『__builtins__』, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standardbuiltin module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1>>> print eval(x+1)2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with exec as the mode argument, eval()』s return value will be None.

Hints: dynamic execution of statements is supported by the exec statement. Execution of statements from a file is supported by the execfile() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

在之前的compile函數里用個這個函數,其實就是將string當做python語句然後運行返回結果。global和local參數代表著調用的命名空間。先找local後找global,如果都為空的話,語句會在當前運行環境下開始找。

25. execfile(filename[, globals[, locals]])

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module. [1]

The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are passed as globals and locals, the code will be executed as if it were embedded in a class definition.

If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function』s locals.

這個函數和exec類似,只是它接收的是一個文件而不是string。它讀取file文件,當做一些列python語句來執行。


推薦閱讀:

8、Templates知識點總結
R vs Python:R是現在最好的數據科學語言嗎?
1000+收藏了!小白自學Python一本通
從數據角度探究《前任3》為什麼這麼火爆

TAG:Python |