我从没系统地学习过 Python,我决定借此契机总结一下我个人不常用的 Python 技巧,以备后用。
Python
Decorator
def release(func):
def inner(pokemon):
print "Release pokemon!"
func(pokemon)
print "Pokemon is released!"
return inner
@release
def getPokemon(pokemon):
print pokemon + "!"
getPokemon("Pikachu")
Special Function Parameters
def listPokemons(*args, **kwargs):
print "Pokemons with unknown type:"
print args
print "Pokemons with type:"
print kwargs
listPokemons("Pikachu", "Eevee", dragon="Dratini", ghost="Gengar")
$ python test.py
Pokemons with unknown type:
('Pikachu', 'Eevee')
Pokemons with type:
{'ghost': 'Gengar', 'dragon': 'Dratini'}
Generator
# Using the generator pattern (an iterable)
class firstn(object):
def __init__(self, n):
self.n = n
self.num, self.nums = 0, []
def __iter__(self):
return self
# Python 3 compatibility
def __next__(self):
return self.next()
def next(self):
if self.num < self.n:
cur, self.num = self.num, self.num+1
return cur
else:
raise StopIteration()
sum_of_first_n = sum(firstn(1000000))
Lambda Expression
x = lambda a, b, c : a + b + c
print x(5, 6, 2)
Testing Library
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()