python中关于输出的小问题???

lifreshman 2011-11-14 04:57:33
我的IDLE版本是3.2.1,现在的问题是:
def fun(a,**n):
print(n)
print("stno is classno is: %d name is:%(name)s, content is:%(content)s"%(a,n));

fun(1,name='freshman',content='fadfadf');

第一个打印正常:{'content': 'fadfadf', 'name': 'freshman'}
第二个打印就报错了:
Traceback (most recent call last):
File "<pyshell#137>", line 1, in <module>
fun(1,name='freshman',content='fadfadf');
File "<pyshell#136>", line 3, in fun
print("stno is classno is: %d name is:%(name)s, content is:%(content)s"%(a,n));
TypeError: format requires a mapping

这是为什么啊???
...全文
324 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lifreshman 2011-11-17
  • 打赏
  • 举报
回复
哪位高手帮我看看下面这段八皇后的代码吧,conflict函数明白,queens函数中后面else里面的循环是什么意思啊,没想明白,望高手解答!程序来自python基础教程第2版中179页。
def conflict(state,nextx):
nexty = len(state);
for i in range(nexty):
if( abs(state[i] - nextx) in (0,nexty - i)):
return True;
return False;


def queens(num = 8,state = ()):
for pos in range(num):
if not conflict(state,pos):
if(len(state) == num - 1):
yield(pos,)
else:
for result in queens(num,state+(pos,)):
yield(pos,)+result
panghuhu250 2011-11-16
  • 打赏
  • 举报
回复
a.m = 2,3

相当于:

a.setsize((2,3)) # 注意只有一个参数

lifreshman 2011-11-16
  • 打赏
  • 举报
回复
谢谢各位哈,我再追问一个问题,是关于property函数的。
class test:
def __init__(self):
self.width = 0;
self.height = 0;
def setsize(self,width,height):
self.width = width;
self.height = height;
def getsize(self):
return self.width,self.height;
m = property(getsize,setsize);

>>> a = test();
>>> a.m
(0, 0)
>>> a.m = 2,3 这行代码为什么会报错呢

setsize函数写成
def setsize(self,size):
self.width,self.height = size;就没有错,是为啥捏!
livesguan 2011-11-16
  • 打赏
  • 举报
回复
property函数原型为property(fget=None,fset=None,fdel=None,doc=None),所以根据自己需要定义相应的函数即可。
libralibra 2011-11-15
  • 打赏
  • 举报
回复
**n传入的是个dict,不存在name和content这样的变量,你怎么能直接用?
你得把**n解包
调试通过


IDLE 2.6.6
>>> def fun(a,**n):
print n
print 'stno is classno is: %d name is: %s, content is %s' % (a,n['name'],n['content'])


>>> fun(1,name='freshman',content='fadfadf')
{'content': 'fadfadf', 'name': 'freshman'}
stno is classno is: 1 name is: freshman, content is fadfadf
>>>
askandstudy 2011-11-14
  • 打赏
  • 举报
回复
print("stno is classno is: name is:%(name)s, content is:%(content)s"%(n))
这样可以的,不知道是不是字典变量不能同时跟普通变量一起使用呢?没有看到过这方面的介绍
JacksonLv 2011-11-14
  • 打赏
  • 举报
回复
你用了3个格式化符号%~,元组里只有2个变量,他们必须是一一对应的。

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧