请教关于python语言的一个小问题

火麒噬日 2010-05-31 09:05:16
记得javascript等一些脚本都支持如下功能:
一句语句,正常写法是:
a1.Text = "sssss";
a1.Text = "bbbbb";
也可以有反射函数


for i = 0 ; i < 10 ; i++;
exe("a"+i+".Text = 100");
等价于敲代码
a1.Text = "100";
a1.Text = "100";
。。。。。
敲100行
请问python有这种功能吗
...全文
146 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
cchb1986 2010-06-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 jimmy1029 的回复:]
python里面也有exec和eval啊
[/Quote]

可以执行的
notax 2010-06-02
  • 打赏
  • 举报
回复


class A:
Text = None

for i in xrange(1, 11):
globals()['a%s'%i] = A()
globals()['a%s'%i].Text = '100'
print 'a%s.Text = %s'%(i, globals()['a%s'%i].Text)


print 'testing a7.Text = %s' %a7.Text

amu9900 2010-06-02
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 whisperlin 的回复:]

问题我昨天晚上自己就解决了
classType = getattr(sys.modules["people"],"People")#这个函数返回people下的People类
#也就是<type 'people.People'>
classObject = new.instance(classType) # 这句话new一个people.People对象
setattr(classObj……
[/Quote]

你是不是自己重写了__new__方法?如果有,那么需要在new方法最后自己调用__init__方法。
当然,默认是自行调用的
amu9900 2010-06-02
  • 打赏
  • 举报
回复

#要使用a1.Text ,那么a1这个对象必须要有Text 这个属性
class A:
Text = None
for i in xrange(1,11):
exec('a%s = A();a%s.Text ="100"' % (i,i))
exec('print "a%s.Text=",a%s.Text' % (i,i))

#输出结果:这时候当前局部名字空间已经有a1.Text等变量的存在,可以使用了
a1.Text= 100
a2.Text= 100
a3.Text= 100
a4.Text= 100
a5.Text= 100
a6.Text= 100
a7.Text= 100
a8.Text= 100
a9.Text= 100
a10.Text= 100
fibbery 2010-06-02
  • 打赏
  • 举报
回复
你用eval试一试
火麒噬日 2010-06-02
  • 打赏
  • 举报
回复
问题我昨天晚上自己就解决了
classType = getattr(sys.modules["people"],"People")#这个函数返回people下的People类
#也就是<type 'people.People'>
classObject = new.instance(classType) # 这句话new一个people.People对象
setattr(classObject,"attr_name","attr_value")#这句话为某个属性赋值
但又有新的问题:
我发觉用new.instance(classType)初始化的类,并没有调用类的__init__函数
但类的所有方法调用都正确,证明确实是这个类,请问有没有什么方法解决啊。




jimmy1029 2010-05-31
  • 打赏
  • 举报
回复
python里面也有exec和eval啊

fibbery 2010-05-31
  • 打赏
  • 举报
回复
Perl中可以使用eval,Python不熟悉,我认为应该也有。去查查看。
fibbery 2010-05-31
  • 打赏
  • 举报
回复
我帮你编辑了一下,你看对不对?
火麒噬日 2010-05-31
  • 打赏
  • 举报
回复
哎,字没打完就不小心按了回车了。
上面
for i = 0 ; i < 10 ; i++;
exe("a"+i+".Text = 100");
等价于敲代码
a1.Text = "100";
a1.Text = "100";
。。。。。
敲100行
请问python有这种功能吗

37,720

社区成员

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

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