30 三 2009
by 抽屉 in Endless Learning , Python Tags: error , Python
麻烦来了,随着继续看Byte-of-python 发现会遇到一些莫名其妙的问题:
class Robot:
'''Represents a robot, with a name.'''
population = 0
def __init__(self,name):
'''Initializes the data.'''
self.name = name
print('(Initializing{0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot
Yeah, they can do that.'''
print('Greetings, my masters call me {0}'.format(self.name))
def howMany(klass):
'''Prints the current population.'''
print('We have {0:d} robots'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3P0')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destory them.")
del droid1
del droid2
Robot.howMany() [code snippet: http://snipt.org/Pll ]
上面这段代码运行结果是:
Traceback (most recent call last):
File “F:\PJ\PythonPJ\objvar.py”, line 1, in <module>
class Robot:
File “F:\PJ\PythonPJ\objvar.py”, line 34, in Robot
droid1 = Robot(‘R2-D2′)
NameError: name ‘Robot’ is not defined
奇怪,只好再检查一次代码中有没有一些低级错误…暂时还没有什么发现…问题是拷贝PDF中提到的代码也是同样的错误…为什么Robot会没有define…
似乎是缩进的问题,调整了缩进之后的代码:
class Robot:
'''Represents a robot, with a name.'''
population = 0
def __init__(self,name):
'''Initializes the data.'''
self.name = name
print('(Initializing{0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot
Yeah, they can do that.'''
print('Greetings, my masters call me {0}'.format(self.name))
def howMany(klass):
'''Prints the current population.'''
print('We have {0:d} robots'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3P0')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destory them.")
del droid1
del droid2
Robot.howMany() [code snippet: http://snipt.org/Plm ]
这下可以initialize Robot了。可是问题又来,
(InitializingR2-D2)
Greetings, my masters call me R2-D2
Traceback (most recent call last):
File “F:\PJ\PythonPJ\objvar.py”, line 36, in <module>
Robot.howMany()
TypeError: howMany() takes exactly 1 positional argument (0 given)
**Note:本文中用Snipt.org输出的代码,在RSS阅读器中没法输出…
27 三 2009
by 抽屉 in Endless Learning , Python Tags: error , Python , question , zip
最近不知道为什么有回头开始看”Byte of Python V1.91″ 今天在读到72页“The solution”的时候遇到了一个问题。需要用python来写一段代码,备份系统的某个,或者某些文件夹。
原文的代码是这样的:
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with
spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be
using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED') [code snippet: http://snipt.org/Ooi ]
我做了些许改动来符合我的现实状况:
import os
import time
source = 'F:\\PJ\PythonPJ'
target_dir = 'F:\\PJ\backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr".format(target, ' '.join(source))
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED') [code snippet: http://snipt.org/Ooh ]
可是,当我在Console中运行backup.py的时候,系统提示“zip I/O error: Invalid argument”… 奇怪了。Google得到的结果大多是当在压缩某个大文件的时候才出现这样的错误。而我的目标文件夹根本就只有5KB而已啊!
于是在“if os.system(zip_command) == 0:”之前加入了一句“print(zip_command)”看一下到底执行的zip命令是什么东西
import os
import time
source = ['F:\\PJ\PythonPJ']
target_dir = 'F:\\PJ\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
print(zip_command)
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED') [code snippet: http://snipt.org/Ooj ]
终于,被我看到输出的命令是”zip -qr F:\PJackup\20090327162409.zip F:\PJ\PythonPJ” 我的目标路径变成了乱码…看来是“\b”被转义了…于是把backup变成了Backup。就没有问题啦。
另外,想如果下次还碰到这样的转义状况怎么办? 把路径改成 F:\\PJ\\backup也是一样OK哒
24 五 2007
by 抽屉 in Python , 蝙蝠人也有春天
记得很久以前就买了Python的书,但是翻过几页之后就被放在了一旁。直到这次搬家整理的时候这本书才重建天日。不过为什么我在学习Ruby的同时又开始看Python的教程呢? 或许是因为打赌的关系,又或许是因为别的什么原因,我不记得了。
在看Python的教程的时候,发现lambda可以完成很多任务。它到底是一个什么样的东西呢?在Google中搜索,对lambda有很多种称呼,比如函数,运算符,方式,关键字等等。一般来讲,lambda的作用是用来定义一个小的函数,这个和def不同。据说Lisp语言也有这样的功能,不过在我之前接触到的有限的语言中没有这样的东西。
lambda很灵活,可以用在任何需要函数的地方:
>>>def f(x):
… return x*2
…
>>> f(2)
4
定义一个函数f(x),f(x)=x*2. 用lambda来表达就是:
>>> f=lambda x: x*2
>>> f(2)
4
这个函数没有函数名,lambda的结果被赋值给变量f调用。
不过这个lambda在我这样的新手阅读代码的时候实在有些费力,每次看到都要反映一下才能明白过来是怎么一个函数。不过据说这个函数在将来会被去除,我觉得,虽然这是一个很方便的方法,但是移除这个lambda也不一定是一件不好的事情。
Technorati Tags: python , lambda
近期评论