class Engine(object):
def captcha(self, url):
'''从url处获得验证码'''
# get captcha from url
# ...
self.captcha = raw_input('Enter the captcha: ')
return self
e = Engine()
e.captcha('http://website/captcha') # first time
print 'You entered captcha: %s' % e.captcha
e.captcha('http://website/captcha') # second time
print 'You entered captcha: %s' % e.captcha
代码看起来很正常,但运行时却显示错误:
Enter the captcha: <<ea859>># 输入验证码
You entered captcha: <<ea859>>
Traceback (most recent call last):
File "test.py", line 11, in <module>
e.captcha('http://website/captcha') # second time
TypeError: 'str' object is not callable
class Engine(object):
def get_captcha(self, url):
'''从url处获得验证码'''
# get captcha from url
# ...
self.captcha = raw_input('Enter the captcha: ')
return self
e = Engine()
e.get_captcha('http://website/captcha') # first time
print 'You entered captcha: %s' % e.captcha
e.get_captcha('http://website/captcha') # second time
print 'You entered captcha: %s' % e.captcha
list comprehension
我要导入一个联系人列表,每个联系人有name, mobile, address, im, 并且可能有多个备份mobile,假设每个字段以空格分开,多个备份mobile之前以逗号分开。以下是其代码:
from StringIO import StringIO
def is_mobile(mobile):
return len(mobile) == 11
def import_contacts(file):
for line in file.readlines():
parts = line.strip().split()
name = parts[0]
mobile = parts[1]
address = parts[2]
im = parts[3]
backup_mobiles = [ mobile for mobile in parts[4].split(',') if is_mobile(mobile) ]
print 'importing contact: %s, mobile=%s' % (name, mobile)
import_contacts(StringIO('''marlon 13511002222 beijing marlon@gmail.com 13711112222,13822224444'''))
from StringIO import StringIO
def is_mobile(mobile):
return len(mobile) == 11
def import_contacts(file):
for line in file.readlines():
parts = line.strip().split()
name = parts[0]
mobile = parts[1]
address = parts[2]
im = parts[3]
backup_mobiles = [ m for m in parts[4].split(',') if is_mobile(m) ]
print 'importing contact: %s, mobile=%s' % (name, mobile)
import_contacts(StringIO('''marlon 13511002222 beijing marlon@gmail.com 13711112222,13822224444'''))