1. 每个python文件至少包含一个class, 所有的逻辑算法都包含在类的函数中。
2. 函数间传递的参数最好用全局变量,就是在init中定义self.xxx. 对外输出的结果一般也保存在全局变量中。
3. 每个文件必须有一个main函数,如果是库文件则测试代码可以写在main函数中方便调试。
==example==
#!/usr/bin/python
import smtplib,sys
from email.Message import Message
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
import getopt
class dogmail:
def __init__(self):
self.subject = ""
self.fromAdd = ""
self.toAdd = ""
self.CcAdd = ""
self.mailText = ""
self.imagePath = []
self.exchange = "rnd-mx01.hello.com"
self.internet = "mail.gamil.com"
self.mailtype = 1
def htmlMail(self):
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = self.subject
msgRoot['From'] = self.fromAdd
msgRoot['To'] = self.toAdd
msgRoot['Cc'] = self.CcAdd
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText(self.mailText, _subtype='html',_charset='gb2312')
msgAlternative.attach(msgText)
if len(self.imagePath) != 0:
for x in self.imagePath:
fp = open(x, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
imageId = "<image%s>" % str(self.imagePath.index(x)+1)
msgImage.add_header('Content-ID', imageId)
msgRoot.attach(msgImage)
return msgRoot.as_string()
def plainMail(self):
msgRoot = Message()
msgRoot['Subject'] = self.subject
msgRoot['From'] = self.fromAdd
msgRoot['To'] = self.toAdd
msgRoot['Cc'] = self.CcAdd
msgText = MIMEText(self.mailText, _subtype='plain', _charset='gb2312')
return msgRoot.as_string()[:-1]+msgText.as_string()
def send(self,msg = ""):
#body=MIMEText(body, _subtype='plain', _charset='gb2312')
server = 0
if self.mailtype == 1:
server = smtplib.SMTP(self.exchange)
else:
server = smtplib.SMTP(sefl.internet)
print "hello"
#server.set_debuglevel(1)
server.sendmail(self.fromAdd, self.toAdd, msg)
server.quit()
def usage(self):
print 'toAdd = aa,bb,cc'
def main():
aa = dogmail()
aa.subject = "just a test mail"
aa.fromAdd = "d...@dogmail.com"
aa.toAdd = "onmy...@google.com"
aa.mailText = 'Hello, I am there'
aa.imagePath = ["aa.jpg","bb.jpg"]
aa.send(aa.plainMail())
if __name__ == "__main__":
main()
--
提供定制Clearcase脚本服务。
完了,看来我写的代码95%以上都是不好的,呜呜~~
--
Qiangning Hong
http://www.douban.com/people/hongqn/
有P友提出怎样才能写出比较好的Python代码呢?我有一点经验,大家讨论讨论。真理越辩越明。
1. 每个python文件至少包含一个class, 所有的逻辑算法都包含在类的函数中。
2. 函数间传递的参数最好用全局变量,就是在init中定义self.xxx. 对外输出的结果一般也保存在全局变量中。
3. 每个文件必须有一个main函数,如果是库文件则测试代码可以写在main函数中方便调试。
2009/1/14 free. wang <fre...@gmail.com>:
是啊,怎么和我的风格一点都不一样呢?
--
I like python!
UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/
UliWeb <<simple web framework>>: http://uliwebproject.appspot.com
My Blog: (new)http://http://hi.baidu.com/limodou
(old)http://www.donews.net/limodou
通过楼主的教诲, 经过艰苦卓绝的努力, 我终于光荣地加入了脱离了低级趣味的 pythonerrrr。
==example==
#!/usr/bin/python
import smtplib, sys
from email.Message import Message
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
class Instance(object): # 每个python文件至少包含一个 class
pass
def dogmail(**args):
self = object.__new__(Instance)
def __init__(self): pass # 略
def htmlMail(self): pass # 略
def plainMail(self): pass # 略
def send(self,msg = ""): pass # 略
def usage(self): pass
# return type('dog_mail', (), locals())()
__init__(self)
return self
if __name__ == "__main__":
aa = dogmail()
aa.subject = "just a test mail"
aa.fromAdd = "d...@dogmail.com"
aa.toAdd = "onmywa...@google.com"
aa.mailText = 'Hello, I am there'
aa.imagePath = ["aa.jpg","bb.jpg"]
aa.send(aa.plainMail())
> --
> Qiangning Honghttp://www.douban.com/people/hongqn/
2009/1/13 OnMyWay <onmy...@gmail.com>:
老沈!你就表掺合了!你是 IOP 教派的:
http://wiki.woodpecker.org.cn/moin/PyIOP
大家都知道的!
Python 从诞生开始就没有想过象JAVA 那样儿要求写成什么规范的的代码!
是否好,永远有两个并行的标准:
- 运行无碍,效率不错
- 辨读无阻,容易分享
存乎一心,无有外规的!
--
http://zoomquiet.org
'''过程改进乃是催生可促生靠谱的人的组织!'''
多吃菜,少喝酒;听老婆的话,跟党走!
--------------------------------------------------
From: "Zoom.Quiet" <zoom....@gmail.com>
Sent: Wednesday, January 14, 2009 10:16 AM
To: <pyth...@googlegroups.com>
Subject: [CPyUG:76874] Re: python的代码写成啥样才算好?我的一点经验。
--
http://zoomquiet.org
'''过程改进乃是催生可促生靠谱的人的组织!'''
usage 7-zip to replace WinRAR/WinZip; You can get the truely Freedom 4 software.
--
http://zoomquiet.org
'''过程改进乃是催生可促生靠谱的人的组织!'''
金山常年招聘Py/C++人才! http://bit.ly/UoTV 简历直投俺就成;-)
我来说下我的观点:
1. Python的编程,class不是第一类的,所以并不强调你要写个类。适用就好。关键是看你的程序的复杂程度,另外是否适合使用面向对象方式来处理。
2. 不鼓励使用全局变量,而是通过参数来传递。这样才是松耦合,程序的变化对其它的部分影响才会小。
3. main()要不要是看要求。有些就是供别人使用的,可以没有main()。
多写一个class多几行字没有那么极端吧。主要是比较易懂,分割明晰。
>>
>> 2. 函数间传递的参数最好用全局变量,就是在init中定义self.xxx. 对外输出的结果一般也保存在全局变量中。
>
> 这个全局变量是指什么?module 的?class 的?object 的?
class的。
>>
>> 3. 每个文件必须有一个main函数,如果是库文件则测试代码可以写在main函数中方便调试。
>
> 测试代码的话,有时候单独分离出来也许会是更好的组织结构。
我的理解是:如果是大型软件的话可能会更好。但是对于就几个小功能的脚本,自带测试代码还是比较方便的。
--
提供定制Clearcase脚本服务。
--
提供定制Clearcase脚本服务。
2009/1/14 smallfish <smal...@live.cn>:
> 说的好
> 第一正常运行,效率还不来
> 第二自己看着代码还是蛮顺眼
> 第三就是按照啥啥规范,啥啥命名。。。
> --
> blog : http://hi.baidu.com/smallfish7788
> bbs : http://bbs.chinaunix.net/forum-55-1.html
> smallfish / xiaoyu9805119
>
--
提供定制Clearcase脚本服务。
On 1月14日, 上午11时16分, Joe <dog...@gmail.com> wrote:
> 他就是那个移动请的国学大师,90%都是在忽悠人的所谓大师。
>
> 2009/1/14 Zoom. Quiet <zoom.qu...@gmail.com>
>
> > 2009/1/14 Joe <dog...@gmail.com>:
>
> > 大妈呀,他是在空谈,没有干货的人就是这样,难听点就是在吹牛。只谈结果不谈过程有什么好谈的?大家需要的是如何去渔,不是拿几条现成的鱼来忽悠人。空谈是没有 意义的,从这个角度上说,楼主的做法很让人赞美。
>
> > 你不用 底回复 不知道你说的"他" 是谁哪,,,
>
> > > 2009/1/14 Zoom. Quiet <zoom.qu...@gmail.com>
>
> > >> 2009/1/14 Joe <dog...@gmail.com>:
>
> > 有一次去移动vip客户讲座,那次是一个国学大师某某在上面谈,说他如何厉害,如何牛逼,如何把老总们的子女教育的听话,其详细描述了这些高干子女在听了他的课 之后的表现,如何如何完美,老总们如何惊叹于他讲课的效果。但对于他是如何做到这一点的却闭口不谈,这不是忽悠人扯淡吗?
>
> > >> 鱼和渔的关系,
> > >> 你现在只认鱼,不管漁,自然感觉在忽悠你了,,,
>
> > >> > 2009/1/14 Joe <dog...@gmail.com>
>
> > >> >> 楼主关注的是如何写好代码,而不是关注于某个标准
>
> > 某些大牛可以具体的把某个标准的详细内容写出来分享啊,不要扯题,不要纠纷于某个标准,现实情况是,像我这样半路出身的人哪个标准也没够上,就别提这标准那标准 了。
>
> > >> >> 俺的观点:
>
> > >> >> 我支持楼主这样具体实在帖子,而不支持貌似在捣乱、谈标准,而不具体实在内容的回复。
>
> > >> >> 2009/1/14 smallfish <smallf...@live.cn>
>
> > >> >>> 说的好
> > >> >>> 第一正常运行,效率还不来
> > >> >>> 第二自己看着代码还是蛮顺眼
> > >> >>> 第三就是按照啥啥规范,啥啥命名。。。
> > >> >>> --
> > >> >>> blog :http://hi.baidu.com/smallfish7788
> > >> >>> bbs :http://bbs.chinaunix.net/forum-55-1.html
> > >> >>> smallfish / xiaoyu9805119
>
> > >> >>> --------------------------------------------------
> > >> >>> From: "Zoom.Quiet" <zoom.qu...@gmail.com>
> > >> >>> Sent: Wednesday, January 14, 2009 10:16 AM
> > >> >>> To: <pyth...@googlegroups.com>
> > >> >>> Subject: [CPyUG:76874] Re: python的代码写成啥样才算好?我的一点经验。
>
> > >> >>> > 2009/1/14 沈崴 <wilei...@gmail.com>
觉得随手写的模块加个 main() 供命令行测试挺好,
而随手写的脚本,将执行放在 main() 里边而不是顺序,也方便随时作为模块来使用
(我以前贴了个 pyrex 编译工具,也是图方便用 main() 作为入口)
以楼主给出的例子来说,使用全局变量传递参数与函数自身的功能逻辑不符,因为
其中有些函数的工作是会受到函数之外变量取值的影响,那么就建议将这种影响显
式地标记为函数的输入参数更为清晰。除非与函数工作细节相关的参数正好是该对
象具有的内部特性,才可以以对象实例属性的方式来设置而不是输入参数。
--
----------------------------------------
Personal Site: http://www.elias.cn
----------------------------------------
我不这么认为。衡量代码的标准有许多,专门有pep8是针对python的代码风格的,但它只是风格而已。建议可以看一下。
好的代码不只有良好的风格,清晰我认为是第一性的,而做到清晰,有时是与代码量少相矛盾的。perl的代码量少,但是可读性比较差。一行式的代码量少,可读性也很差。
就代码本身来说,好还是不好本身是很模糊的。但它可能是一种综合性的评价,比如要满足如下的条件(我自已想的):
1. 代码要正确
2. 代码要清晰,具有良好的风格
3. 要有足够的注释
4. 功能划分要合理
5. 不要玩过多的技巧
。。。
可能还有很多
Robert C. Martin introduces his book, Clean Code, and polls
experienced programmers -- including Bjarne Stroustrup, Grady Booch,
Dave Thomas, and Ward Cunningham -- on what their definition of "Clean
Code" is.
"This chapter is from the book Clean Code: A Handbook of Agile
Software Craftsmanship"
You are reading this book for two reasons. First, you are a
programmer. Second, you want to be a better programmer. Good. We need
better programmers.
...
http://www.informit.com/store/product.aspx?isbn=0132350882
On 1月14日, 上午10时16分, Zoom.Quiet <zoom.qu...@gmail.com> wrote:
> 2009/1/14 沈崴 <wilei...@gmail.com>
说太多都是空谈,秀一下我写的代码,抛砖引玉,这段代码前几天发过一次了
因为暂时可以满足需求,所以没有修改
#coding:utf-8
from email.mime.text import MIMEText
import smtplib
class Gamil (object ):
def __init__ (self ,account,password):
self.account=account
self.password=password
self.email="%s...@gmail.com" % account
On 1月15日, 上午8时31分, "liuxin9...@gmail.com" <liuxin9...@gmail.com>
wrote:
有P友提出怎样才能写出比较好的Python代码呢?我有一点经验,大家讨论讨论。真理越辩越明。
1. 每个python文件至少包含一个class, 所有的逻辑算法都包含在类的函数中。
2. 函数间传递的参数最好用全局变量,就是在init中定义self.xxx. 对外输出的结果一般也保存在全局变量中。
3. 每个文件必须有一个main函数,如果是库文件则测试代码可以写在main函数中方便调试。
从这个意义上来说,现在很多邮件列表里最讨厌的事情就是太多重复问题。每周都有人来讨论如何重复“干货”。
> > 大妈呀,他是在空谈,没有干货的人就是这样,难听点就是在吹牛。只谈结果不谈过程有什么好谈的?大家需要的是如何去渔,不是拿几条现成的鱼来忽悠人。空谈是没有 意义的,从这个角度上说,楼主的做法很让人赞美。
从这个意义上来说,现在很多邮件列表里最讨厌的事情就是太多重复问题。每周都有人来讨论如何重复"干货"。
2009/1/13 OnMyWay <onmy...@gmail.com>:
>
> 有P友提出怎样才能写出比较好的Python代码呢?我有一点经验,大家讨论讨论。真理越辩越明。
>
> 1. 每个python文件至少包含一个class, 所有的逻辑算法都包含在类的函数中。
> 2. 函数间传递的参数最好用全局变量,就是在init中定义self.xxx. 对外输出的结果一般也保存在全局变量中。
> 3. 每个文件必须有一个main函数,如果是库文件则测试代码可以写在main函数中方便调试。
>
> ==example==
> #!/usr/bin/python
> import smtplib,sys
> from email.Message import Message
> from email.MIMEText import MIMEText
> from email.MIMEMultipart import MIMEMultipart
> from email.MIMEImage import MIMEImage
> import getopt
>
> class dogmail:
> def __init__(self):
> self.subject = ""
> self.fromAdd = ""
> self.toAdd = ""
> self.CcAdd = ""
> self.mailText = ""
> self.imagePath = []
> self.exchange = "rnd-mx01.hello.com"
> self.internet = "mail.gamil.com"
> self.mailtype = 1
> def htmlMail(self):
> msgRoot = MIMEMultipart('related')
> msgRoot['Subject'] = self.subject
> msgRoot['From'] = self.fromAdd
> msgRoot['To'] = self.toAdd
> msgRoot['Cc'] = self.CcAdd
> msgRoot.preamble = 'This is a multi-part message in MIME format.'
>
> msgAlternative = MIMEMultipart('alternative')
> msgRoot.attach(msgAlternative)
> msgText = MIMEText('This is the alternative plain text message.')
> msgAlternative.attach(msgText)
>
> msgText = MIMEText(self.mailText, _subtype='html',_charset='gb2312')
> msgAlternative.attach(msgText)
>
> if len(self.imagePath) != 0:
> for x in self.imagePath:
> fp = open(x, 'rb')
> msgImage = MIMEImage(fp.read())
> fp.close()
> imageId = "<image%s>" % str(self.imagePath.index(x)+1)
> msgImage.add_header('Content-ID', imageId)
> msgRoot.attach(msgImage)
> return msgRoot.as_string()
>
> def plainMail(self):
> msgRoot = Message()
> msgRoot['Subject'] = self.subject
> msgRoot['From'] = self.fromAdd
> msgRoot['To'] = self.toAdd
> msgRoot['Cc'] = self.CcAdd
> msgText = MIMEText(self.mailText, _subtype='plain', _charset='gb2312')
> return msgRoot.as_string()[:-1]+msgText.as_string()
>
> def send(self,msg = ""):
> #body=MIMEText(body, _subtype='plain', _charset='gb2312')
> server = 0
> if self.mailtype == 1:
> server = smtplib.SMTP(self.exchange)
> else:
> server = smtplib.SMTP(sefl.internet)
> print "hello"
> #server.set_debuglevel(1)
> server.sendmail(self.fromAdd, self.toAdd, msg)
> server.quit()
> def usage(self):
> print 'toAdd = aa,bb,cc'
>
> def main():
> aa = dogmail()
> aa.subject = "just a test mail"
> aa.fromAdd = "d...@dogmail.com"
> aa.toAdd = "onmy...@google.com"
> aa.mailText = 'Hello, I am there'
> aa.imagePath = ["aa.jpg","bb.jpg"]
> aa.send(aa.plainMail())
>
> if __name__ == "__main__":
> main()
>
> --
> 提供定制Clearcase脚本服务。
>
> >
>
为啥要把测试放在main里....
不用掀桌子那么激动,写程序需要心平气和。
现在进行时的设计方式是什么?
#!/usr/bin/python
# -*- coding: cp936 -*-
#################################
# Written by caocao #
# cao...@eastday.com #
# http://nethermit.yeah.net #
#################################
import sys, string, os
from types import *
import MySQLdb
print "Written by caocao"
print "cao...@eastday.com"
print "http://nethermit.yeah.net"
print
def iif(expression, whenTrue, whenFalse):
if expression:
return whenTrue
else:
return whenFalse
class mysqlTest:
def __init__(self, host="localhost", user="root", passwd="", db=""):
self.connection=None
self.host=host
self.user=user
self.passwd=passwd
self.db=db
self.result=None
print "-"*40
print "MySQL Shell v 1.0"
print "Usage: python mysql.shell.py [host] [user] [passwd(% is empty)] [db]"
print "Connect..."
try:
self.connection=MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db)
except:
print "Can't connect to mysql server.\nPlease make sure your username or password is right."
sys.exit(1)
print "-"*40
print self.printComment("connection", "get_server_info")
print self.printComment("connection", "get_host_info")
print self.printComment("connection", "get_proto_info")
print self.printComment("connection", "info")
print self.printComment("connection", "character_set_name")
print self.printComment("connection", "thread_id")
print self.printComment("connection", "stat")
def __del__(self):
if self.connection!=None:
self.connection.close()
print "-"*40
print "Quit..."
def printComment(self, instance, function):
return "%s = %s" % (string.rjust(function, 18), eval("self."+instance+"."+function+"()"))
def printAll(self):
output, row="", self.result.fetch_row(0)
for i in range(self.result.num_fields()):
output+=repr(self.result.describe()[i][0])+"\n"
for i in range(self.result.num_rows()):
for j in range(self.result.num_fields()):
output+=iif(type(row[i][j]) is StringType, row[i][j], repr(row[i][j]))+"\n"
return output
def runSQL(self, queryString="show databases"):
print "-"*40
try:
self.connection.query(queryString)
except:
print "Can't run sql."
else:
self.result=self.connection.store_result()
print self.printComment("connection", "field_count")
print self.printComment("connection", "affected_rows")
print self.printComment("connection", "insert_id")
print self.printComment("result", "num_fields")
print self.printComment("result", "num_rows")
print self.printComment("result", "field_flags")
print "-"*40
print self.printAll()
if __name__=="__main__":
argArray=sys.argv
del argArray[0]
test=eval(("mysqlTest(\"%s\")" % "\",\"".join(argArray)).replace("%", ""))
while True:
try:
command=string.strip(raw_input("PS mysql>"), " ")
commandLow=string.lower(command)
except EOFError:
break
else:
if commandLow=="exit" or commandLow=="quit":
break
elif commandLow=="":
continue
else:
test.runSQL(command)
2009/1/16 头太晕 <tor...@gmail.com>:
--
提供定制Clearcase脚本服务。
我觉这个貌似是设计问题,并不是代码问题。
2009/1/16 刘鑫 <marc...@gmail.com>:
>
>
> 2009/1/15 OnMyWay <onmy...@gmail.com>
>>
>> 不用掀桌子那么激动,写程序需要心平气和。
>> 现在进行时的设计方式是什么?
>
>
> 只是调侃一下赤壁哈,不是人参公鸡^_^。
> 轻量一些好,以前写C#程序的时候,总是不自觉搞得很重,最后发现时间都浪费在class上了,运行时效率和开发时效率都不理想。
> 把一个模块就看作是一个运行时的对象,把Python VM本身看作是一个Runtime Framework,会觉得世界美好很多。
>
>>
--
提供定制Clearcase脚本服务。