450磅图书馆计划 [英] 450 Pound Library Program

查看:60
本文介绍了450磅图书馆计划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了进一步尝试学习一些Python,我已经采取了一点点

库程序

http://groups.google.com/group/comp....a9ccf1bc136f84

我写了并添加了几个功能。读者现在退出,他们已经阅读了图书馆的所有书籍。书籍知道他们已经阅读了多少次b
。最重要的是,您现在可以创建自己的书籍列表来阅读



再一次,所有这一切的重点是习惯于编程Python。

所以虽然程序很简单,但任何有关样式,结构,

等的反馈都会非常感激。我是Java的皈依者,所以我已经在某处找到了一些无意识的爪哇人。帮我搞定

摆脱它!


这是新改进的程序:

So in a further attempt to learn some Python, I''ve taken the little
Library program
(http://groups.google.com/group/comp....a9ccf1bc136f84)
I wrote and added several features to it. Readers now quit when they''ve
read all the books in the Library. Books know how many times they''ve
been read. Best of all, you can now create your own list of books to
read!

Again, the point of all this is to get used to programming in Python.
So although the program is trivial, any feedback on style, structure,
etc. would be much appreciated. I''m a convert from Java, so I''ve
probably got some unconscious Javanese in there somewhere. Help me get
rid of it!

Here''s the new, improved program:

展开 | 选择 | Wrap | 行号

推荐答案

只是一些风格的笔记...
just a few style notes...
def checkOutBook(self,readerName):
"''从列表前面删除书籍,如果没有可用的书籍则会阻止''"


我不明白''应该暗示什么。如果您想要使用三重引号,则需要使用''''''或'''''"。

然后该字符串可以包含换行符。 (也许你有

a非常愚蠢的电子邮件客户端/新闻客户/编辑/无论如何

用'''替换'''''?请放松或使用"""。)


另外,请使用足够短的行不要包裹

。换行使代码非常难看。这样做:


def checkOutBook(self,readerName):

"""从列表前面删除书籍,如果没有则阻止

书籍可用。""


[...] for BookFile.readlines()中的行:


在现代Python中你只需写:

for bookFile中的行:

L = line.split(",")#a comma-分隔列表
作者= L [0]
bookName = L [1]


为什么要打扰L?我认为以下内容很清楚,并解决了标题中逗号的问题。另外,请不要在

之间留出一个空格。参见Python风格指南,

PEP 008.


作者,bookName = line.split(",",2)


[...] totalBooks =输入(你想在
库中有多少本书?[1-+ str(len(stacks))+"]" ;)
def checkOutBook(self, readerName):
"''Remove book from the front of the list, block if no books are
available''"
I don''t understand what "'' is supposed to imply. If you
meant to use triple quoting, you need to use '''''' or """.
Then the string can contain line breaks. (Perhaps you have
a really stupid email client/news client/editor/whatever that
replaces '''''' with "''? Please loose that or use """.)

Also, please use lines that are short enough not to wrap
around. Line wrapping makes the code very ugly. Do like this:

def checkOutBook(self, readerName):
"""Remove book from the front of the list, block if no
books are available."""

[...] for line in theBookFile.readlines():
In modern Python you simply write:
for line in theBookFile:
L = line.split (",") # a comma-delimited list
author = L[0]
bookName = L[1]
Why bother with L? The follwing is as clear I think, and solves
the problem of commas in the title. Also, don''t put a space between
the callable and the parenthesis please. See the Python style guide,
PEP 008.

author, bookName = line.split(",", 2)

[...] totalBooks = input("How many books would you like in the
Library?[1-" + str(len(stacks)) + "]")




再次,不要让线条这么长。你不必这样做。

你可以在(),{}和[]内自由地断行,并且相邻

字符串文字会自动连接。


totalBooks =输入(你想要多少本书

"图书馆?[1-%d]"%len(堆栈))



Again, don''t make the lines so long. You don''t have to do that.
You can break lines freely inside (), {} and [], and adjacent
string literals are automatically concatenated.

totalBooks = input("How many books would you like in "
"the Library?[1-%d]" % len(stacks))


mwt写道:
因此,为了进一步尝试学习一些Python,我已经采取了一点点
图书馆计划
http:/ /groups.google.com/group/comp....a9ccf1bc136f84
我写了并添加了几个功能。当读者阅读了图书馆的所有书籍时,读者现在就退出了。书籍知道他们被阅读了多少次。最重要的是,你现在可以创建自己的书籍列表来阅读!

同样,所有这一切的重点是习惯用Python编程。
所以虽然该计划是微不足道的,任何关于风格,结构,
等的反馈将非常感激。我是Java的转换者,


欢迎! - )

所以我可能在那里找到了一些无意识的爪哇人。帮我搞定吧!


好​​吧,除了namingConventions(vs naming_conventions)之外,我没有在你的代码中发现过多的java bism。

这里这是一个新的,改进的程序:
[code]
#!/ usr / bin / python
#Filename:Library.py
#author:mwt
#Feb,2006

导入线程
导入时间
导入线程
导入随机

类库2:


不推荐使用旧式类,而是使用新式类:

class Library2(object):

def __init __(self,listOfBooks,totalBooks) :
self.stacks = listOfBooks


如果它是一本书的集合,为什么不称它为书籍?

self.cv = threading.Condition()
self.totalBooks = totalBooks


什么是''totalBooks''?

def checkOutBook(self,readerName) :
"''从列表前面删除书籍,如果没有书籍则会阻止
ava ilable"


为什么不使用三引号字符串?

self.cv.acquire()
而len(self.stacks)== 0:
self.cv.wait()
print"%s等待一本书...... %readerName
book = self.stacks.pop(0)


最后一行会在空列表中崩溃(IndexError),然后是

资源可能无法发布...第一步是将其封装在

a try / finally块中。

self.cv.release()
返回书

def returnBook(self,returnBook):
"''把书放在列表末尾,通知一本书是否可用''"
已返回Book.wasRead()
self.cv.acquire()
self.stacks.append(returnsBook)
self.cv.notify()
self.cv .release()


你在最后两种方法中有一个反复出现的模式:aquire / do

something / release。你可以在一个方法装饰器中考虑这个因素

(别忘了函数和方法也是对象,所以你可以用它们来做

a *很多*的东西)。

类Reader(threading.Thread):

def __init __(self,library,name,readingSpeed,timeBetweenBooks):
threading.Thread .__ init __(自我)
或:

super(读者,自我).__ init __()


但这不会在这里产生很大的影响

self.library = library
self.name = name
self.readingSpeed = readingSpeed
self.timeBetweenBooks = timeBetweenBooks
self.book ="" ;


您以后使用Reader.book来保存对Book对象的引用,因此它将更明智地用None初始化它。


self.numberOfBooksRead = 0

&''''继续检查和阅读书籍,直到你读完所有内容
图书馆''"
而self.numberOfBooksRead< self.library.totalBooks:
self.book = self.library.checkOutBook(self.name)
print"%s reading%s" %(self.name,self.book.title),
time.sleep(self.readingSpeed)
self.numberOfBooksRead + = 1
self.library.returnBook(self.book)
print"%s完成阅读%s" %(self.name,self.book.title),
print"%s已阅读的书籍数量:%d %(self.name,
self.numberOfBooksRead)
self.bookName =""
time.sleep(self.timeBetweenBooks)
print"%s完成阅读。 " %self.name

类书:
def __init __(自我,作者,标题):
self.author = author
self.title = title
self.numberOfTimesRead = 0
#print"%s,%s" %(self.author,self.title),#print as books

def wasRead(self):
self.numberOfTimesRead + = 1
print已读取%s的次数:%d %(self.title,
self.numberOfTimesRead)

如果__name __ ==" __ main __":


你应该定义一个main()功能,并从这里打电话。

打印\\\
WELCOME到THURMOND STREET公共图书馆>
打印检查哪些图书是可用的... \ n
s / avialable / available /! - )

尝试:
theBookFile = open(" books.txt"," r")#创建自己的
书!


文件名不应该是硬编码的。


(好吧,你可能已经知道了,但我认为最好是

为新手程序员指出这一点)

stacks = [] #a把书放在书架上的地方
在BookFile.readlines()中:
L = line.split(",")#逗号分隔列表


嗯...可能不是最好的格式。如果书中有逗号

title怎么办?提示:标准库中有一个CSV模块。


此外,按照惯例,大写标识符被视为常量

author = L [0]
bookName = L [1]
newBook = Book(作者,bookName)
stacks.append(newBook)


你可以粉碎这一切单行:

stacks = [Book(line.split(",",1)for BookFile中的行]

theBookFile.close()
除了IOError:
print" File not found!"


IOError可能由很多不同的原因造成(比如用户不是

对文件具有读取权限。)所以不要认为找不到文件:


除了IOError,e:

print" could不打开文件%s:%s"%(''books.txt'',e)


您可能还想退出这里...

#string ="你想在图书馆里放几本书?[1-" + str(len(stacks))+"]"
totalBooks = input("
库中你想要多少本书?[1-] + str(len(stacks))+"]")


1 /使用raw_input()和* validate *用户数据


2 /使用字符串格式:

prompt ="在

中你想要多少本书?图书馆? [1-%d] QUOT; %len(stacks)

stacks [totalBooks:len(stacks)] = []
stacks = stacks [:totalBooks]


可能是效率低,但更易读恕我直言。


此外,命名有点误导。

numberOfBooks或booksCount的内容可能会更好。

print"图书馆中的图书数量为:",len(stacks)


你已经用3行调用了len(堆栈)3次。

library = Library2(stacks,totalBooks)


这里的totalBooks有什么用? Library2类可以自己弄明白它是b $ b,所以它没用 - 它反对DRY和SPOT。


提示:给定使用of Library.totalBook,你最好把它变成一个

计算属性


类LibraryN(对象):

booksCount = property(fget = lambda self:len(self.books))

readers = input(&\\;你想要多少读者?)


同上。此外,像readersCount这样的东西会少一些误导(我首先认为它是一个读者对象的集合)

print"读者人数是:读者,对于范围内的我来说是\ n;
(0,读者):
newReader = Reader(库,读者+ str(i),
random.randint(1, 7),random.randint(1,7))


性能提示:首先在本地命名空间中查找名称:


randint = random.randint

for i in range(0,readers):

newReader = Reader(library,

" Reader%d" %i,

randint(1,7),

randint(1,7))

newReader.start()
So in a further attempt to learn some Python, I''ve taken the little
Library program
(http://groups.google.com/group/comp....a9ccf1bc136f84)
I wrote and added several features to it. Readers now quit when they''ve
read all the books in the Library. Books know how many times they''ve
been read. Best of all, you can now create your own list of books to
read!

Again, the point of all this is to get used to programming in Python.
So although the program is trivial, any feedback on style, structure,
etc. would be much appreciated. I''m a convert from Java,
Welcome !-)
so I''ve
probably got some unconscious Javanese in there somewhere. Help me get
rid of it!
Well, apart from namingConventions (vs naming_conventions), I did not
spot too much javaism in your code.
Here''s the new, improved program:
[code]
#!/usr/bin/python
# Filename: Library.py
# author: mwt
# Feb, 2006

import thread
import time
import threading
import random

class Library2:
Old-style classes are deprecated, use new-style classes instead:
class Library2(object):
def __init__(self, listOfBooks, totalBooks):
self.stacks = listOfBooks
If its a collection of books, why not call it ''books'' ?
self.cv = threading.Condition()
self.totalBooks = totalBooks
What is ''totalBooks'' ?
def checkOutBook(self, readerName):
"''Remove book from the front of the list, block if no books are
available''"
Why not using triple-quoted strings ?
self.cv.acquire()
while len(self.stacks) == 0:
self.cv.wait()
print "%s waiting for a book..." %readerName
book = self.stacks.pop(0)
This last line will crash (IndexError) on an empty list, and then the
resource may not be released... A first step would be to enclose this in
a try/finally block.
self.cv.release()
return book

def returnBook(self, returnedBook):
"''put book at the end of the list, notify that a book is
available''"
returnedBook.wasRead()
self.cv.acquire()
self.stacks.append(returnedBook)
self.cv.notify()
self.cv.release()
You have a recurring pattern in the last 2 methods: aquire/do
something/release. You could factor this out in a method decorator
(don''t forget that functions and methods are objects too, so you can do
a *lot* of things with them).
class Reader(threading.Thread):

def __init__(self, library, name, readingSpeed, timeBetweenBooks):
threading.Thread.__init__(self) or :
super(Reader, self).__init__()

but this wouldn''t make a big difference here
self.library = library
self.name = name
self.readingSpeed = readingSpeed
self.timeBetweenBooks = timeBetweenBooks
self.book = ""
You later user Reader.book to hold a reference to a Book object, so it
would be wiser to initialize it with None.
self.numberOfBooksRead = 0

def run(self):
"''Keep checking out and reading books until you''ve read all in
the Library''"
while self.numberOfBooksRead < self.library.totalBooks:
self.book = self.library.checkOutBook(self.name)
print "%s reading %s" %(self.name, self.book.title),
time.sleep(self.readingSpeed)
self.numberOfBooksRead += 1
self.library.returnBook(self.book)
print "%s done reading %s" %(self.name, self.book.title),
print"Number of books %s has read: %d" %(self.name,
self.numberOfBooksRead)
self.bookName = ""
time.sleep(self.timeBetweenBooks)
print "%s done reading." %self.name

class Book:
def __init__(self, author, title):
self.author = author
self.title = title
self.numberOfTimesRead = 0
#print "%s,%s" % (self.author, self.title),#print as books are
loaded in

def wasRead(self):
self.numberOfTimesRead += 1
print "Number of times %s has been read: %d" %(self.title,
self.numberOfTimesRead)

if __name__=="__main__":

You should define a main() function and call it from here.
print "\nWELCOME TO THE THURMOND STREET PUBLIC LIBRARY"
print "Checking which books are avialable...\n" s/avialable/available/ !-)
try:
theBookFile = open("books.txt", "r")#Create your own list of
books!
Filenames should not be hardcoded.

(Ok, you probably know this already, but I thought it would be better to
point this out for newbie programmers)
stacks = []#a place to put the books
for line in theBookFile.readlines():
L = line.split (",") # a comma-delimited list
Mmm... may not be the best format. What if there are commas in the book
title ? Hint : there''s a CSV module in the standard lib.

Also, by convention, UPPERCASE identifiers are considered as CONSTANTS
author = L[0]
bookName = L[1]
newBook = Book(author, bookName)
stacks.append(newBook)
You can smash all this in a single line:
stacks = [Book(line.split(",", 1) for line in theBookFile]
theBookFile.close()
except IOError:
print "File not found!"
An IOError can result from a lot of different reasons (like user not
having read access on the file). So don''t assume the file was not found:

except IOError, e:
print "Could not open file %s : %s" % (''books.txt'', e)

You may also want to exit here...
#string = "How many books would you like in the Library?[1-" +
str(len(stacks)) + "]"
totalBooks = input("How many books would you like in the
Library?[1-" + str(len(stacks)) + "]")
1/ use raw_input() and *validate* user data

2/ use string formatting:
prompt = "How many books would you like in the "
" Library? [1-%d]" % len(stacks)
stacks[totalBooks: len(stacks)] = [] stacks = stacks[:totalBooks]

May be less efficient, but much more readable IMHO.

Also, the naming is somewhat misleading. Something along the line of
numberOfBooks or booksCount would probably be better.
print "Number of books in the Library is:", len(stacks)
You''ve called len(stacks) 3 times in 3 lines.
library = Library2(stacks, totalBooks)
What''s the use of totalBooks here ? The Library2 class can figure it out
by itself, so it''s useless - and it goes against DRY and SPOT.

hint: given the use of Library.totalBook, you''d better make it a
computed attribute

class LibraryN(object):
booksCount = property(fget=lambda self: len(self.books))
readers = input("\nHow many readers would you like?")
idem. Also, something like readersCount would be less misleading (I
first thought it was a collection of Reader objects)
print "Number of readers is:", readers, "\n"
for i in range(0,readers):
newReader = Reader(library, "Reader" + str (i),
random.randint(1,7), random.randint(1,7))
performance hint: names are first looked up in the local namespace:

randint = random.randint
for i in range(0, readers):
newReader = Reader(library,
"Reader%d" % i,
randint(1,7),
randint(1,7))
newReader.start()




我的2美分......


(剪辑)


-

bruno desthuilliers

python -c" print''@''。join([''。''。join([w [:: - 1] for w in p .split(''。'')])for'/ o **** @ xiludom.gro'中的
p。分裂(''@ ')])"



My 2 cents...

(snip)

--
bruno desthuilliers
python -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) for
p in ''o****@xiludom.gro''.split(''@'')])"


Magnus Lycka写道:
Magnus Lycka wrote:
只是一些风格的笔记...

( snip)
为什么要打扰L?我认为以下是明确的,并解决了标题中逗号的问题。另外,请不要在可调用和括号之间留一个空格。请参阅Python样式指南,
PEP 008.

作者,bookName = line.split(",",2)
just a few style notes...
(snip)
Why bother with L? The follwing is as clear I think, and solves
the problem of commas in the title. Also, don''t put a space between
the callable and the parenthesis please. See the Python style guide,
PEP 008.

author, bookName = line.split(",", 2)
" toto,tata,tutu" .split(",",2)
[''toto'',''tata'',''tutu'']
"toto, tata, tutu".split(",", 2) [''toto'', '' tata'', '' tutu'']




你想要line.split('','',1)。


- < br $> b $ b bruno desthuilliers

python -c" print''@''。join([''。''。join([w [:: - 1] for w在p.split(''。'')])中'/ o **** @ xiludom.gro'中的
p。分裂(''@'')])"



You want line.split('','', 1) here.

--
bruno desthuilliers
python -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) for
p in ''o****@xiludom.gro''.split(''@'')])"


这篇关于450磅图书馆计划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆