Python基础语法

>>> li1.extend(li2)
>>> li.append(element)
>>> ' '.join(li)
return string
>>> str1.split(' ')
return list
>>> str1.strip()
>>> # f.readline() return a string that contains '\n'
>>> # using strip() to elimate characters that isn't need

A dict and list can be changed by passing it to a function.

Fuction Arguments

Default Arguments

The default values are evaluated at the point of function definition in the defining scope.

The default value is evaluated only once.

Dictionary As Arguments

def foo(**args):
    print args


def bar(a, b):
    print a, b

d = {'a': 1, 'b': 2}

foo(a=1, b=2) # **args means args is a dict, but it accept key word arguments
foo(**d) # when pass a dict to arguments using **d, it unpack it to key word arguments

bar(**d) # same as line above
bar(a=1, b=2) # normal function can pass key word arguments too, but notice it's position

foo(d) # error, must be key word arguments

List arguments can be the same as dictionary, except that it using * symbol.

Iterable

for i in iterable works because iterable has a __iter__() function that returns an object that has next() function.

elif hasattr(iterable, "__getitem__") \
or hasattr(iterable, "__iter__"):

If iterable has attribute __getitem__, then can use iterable[i], or if it attribute __iter__, both case can use for i in iterable to loop.

hasattr

hasattr returns True if an object has public member, public function, or even static function. But private member or private function returns false.

Table Of Contents

Previous topic

The Practice of Programming

Next topic

Frequently Asked Questions

This Page