setattr问题 [英] setattr question

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

问题描述

您好


我有以下代码:


#### builder.py #########

类HtmlBuilder(对象):


@staticmethod

def page(title =''''):

返回HtmlPage(标题)


@staticmethod

def元素(tag,text = None,** attribs):

返回HtmlElement(标签,文字,** attribs)


@staticmethod

def literal(文字):

返回HtmlLiteral(文本)


class HtmlElementFactory(object):


def __init __(self):

标签在[''li'',''ul'']:

setattr(self,tag,HtmlBuilder.element(tag))


#########################

所以我可以做到以下几点:


html = HtmlElementFactory()

ul = html.ul

ul.attrib [''class''] =''default''

for i in range(3):

li = html.li

li.text =''ghfhj''

ul.append(li)

打印ul.to_string()


但我想做的是:


html = HtmlElementFactory()

ul = html.ul(class =''default'')

for i in range (3):

ul.append(html.li(''ghfhj'')

print ul.to_string()


即。将* args和** kwargs传递给HtmlElement构造函数。

有什么建议吗?还是有更好的方式来做这种事吗?


谢谢


Gerard

Hello

I have the following code:

#### builder.py #########
class HtmlBuilder(object):

@staticmethod
def page(title=''''):
return HtmlPage(title)

@staticmethod
def element(tag, text=None, **attribs):
return HtmlElement(tag, text, **attribs)

@staticmethod
def literal(text):
return HtmlLiteral(text)

class HtmlElementFactory(object):

def __init__(self):
for tag in [''li'', ''ul'']:
setattr( self, tag, HtmlBuilder.element(tag) )

#########################

and so I can do the following:

html = HtmlElementFactory()
ul = html.ul
ul.attrib[''class''] = ''default''
for i in range(3):
li = html.li
li.text = ''ghfhj''
ul.append(li)
print ul.to_string()

but what I''d like to do is:

html = HtmlElementFactory()
ul = html.ul( class=''default'' )
for i in range(3):
ul.append( html.li( ''ghfhj'' )
print ul.to_string()

ie. to pass along *args and **kwargs to the HtmlElement constructor.
Any suggestions? Or is there a better way to this kind of thing?

thanks

Gerard

推荐答案

Gerard Flanagan写道:
Gerard Flanagan wrote:
你好

我有以下代码:

## ## builder.py #########
类HtmlBuilder(对象):

@staticmethod
def page(title =''''):
返回HtmlPage(标题)

@staticmethod
def元素(标记,文本=无,**属性):
返回HtmlElement(标记,文本,**属性) )

@staticmethod
def literal(text):
返回HtmlLiteral(文本)


Je ne voispastrèsbienàquoi sert cette classe(àmoinsbien s?r

qu''il y ait d'autre code)。 Pour ce que jevoislà,pourquoi ne pas

appeler directement les classes HtmlPage,HtmlElement et HtmlLiteral?


Err ...我没看到本课程的重点。为什么不直接调用

HtmlPage | Element | Literal类?

class HtmlElementFactory(object):

def __init __(self):
for [''li'',''ul'']中的标签:
setattr(self,tag,HtmlBuilder.element(tag))

##### ####################

所以我可以做到以下几点:

html = HtmlElementFactory()
ul = html.ul
ul.attrib [''class''] =''默认''
我在范围内(3):
li = html.li
li.text =''ghfhj''
ul.append(li)
print ul.to_string()

但我想做的是:

html = HtmlElementFactory()
ul = html.ul(class =''default'')



for i在范围(3)中:
ul.append(html.li(''ghfhj'')
print ul.to_string()


''to_string' '?

让我们看看...... to_string'',一个只有staticmethods的类......

你来自Java,不是吗? - )


(如果是,google forpython不是java,它可能会有所帮助)

ie。将* args和** kwargs传递给HtmlElement构造函数。
有什么建议吗?


是的:将* args和** kwargs传递给HtmlElement构造函数! - )


或者有更好的方法来实现这种事情?
Hello

I have the following code:

#### builder.py #########
class HtmlBuilder(object):

@staticmethod
def page(title=''''):
return HtmlPage(title)

@staticmethod
def element(tag, text=None, **attribs):
return HtmlElement(tag, text, **attribs)

@staticmethod
def literal(text):
return HtmlLiteral(text)
Je ne vois pas très bien à quoi sert cette classe (à moins bien s?r
qu''il y ait d''autre code). Pour ce que je vois là, pourquoi ne pas
appeler directement les classes HtmlPage, HtmlElement et HtmlLiteral ?

Err... I don''t see the point of this class. Why not just calling the
HtmlPage|Element|Literal classes directly ?
class HtmlElementFactory(object):

def __init__(self):
for tag in [''li'', ''ul'']:
setattr( self, tag, HtmlBuilder.element(tag) )

#########################

and so I can do the following:

html = HtmlElementFactory()
ul = html.ul
ul.attrib[''class''] = ''default''
for i in range(3):
li = html.li
li.text = ''ghfhj''
ul.append(li)
print ul.to_string()

but what I''d like to do is:

html = HtmlElementFactory()
ul = html.ul( class=''default'' )

for i in range(3):
ul.append( html.li( ''ghfhj'' )
print ul.to_string()
''to_string'' ?
Let''s see... ''to_string'', a class with only staticmethods in it...
You''re coming from Java, aren''t you ?-)

(if yes, google for "python is not java", it may be helpful)
ie. to pass along *args and **kwargs to the HtmlElement constructor.
Any suggestions?
yes : pass along *args and **kwargs to the HtmlElement constructor !-)

Or is there a better way to this kind of thing?




是的:亲吻(保持简单愚蠢)


真的没有足够的代码抓住你想要做的事情,但是从我看到的情况来看,我会说你有一个任意的错误案例,即b $ b过度复杂化。


有什么问题:


#nb:class是Python中的保留字

ul = HtmlElement(''ul'',css_class =''default'')

for i in range(3):

ul.append(HtmlElement(''li') ','''baaz%d''%i)


#nb2:使用HtmlElement的__str __()方法

print str(ul)


Python的理念是让简单的事情变得简单(别担心,

还有复杂事物的空间 - >描述符,元类等)。


HTH

-

bruno desthuilliers

python -c" print''@'' .join([''。''。join([w [:: - 1] for p in p.split(''。'')])for

p in''o ** ** @ xiludom.gro''。split(''''')])"



yes again : kiss (Keep It Simple Stupid)

There''s not enough code to really grasp what you''re trying to do, but
from what I see, I''d say you''re having a bad case of arbitrary
overcomplexification.

What''s wrong with:

# nb: class is a reserved word in Python
ul = HtmlElement(''ul'', css_class=''default'')
for i in range(3):
ul.append(HtmlElement(''li'', ''baaz%d'' % i)

# nb2: use the __str__() method of HtmlElement
print str(ul)

Python''s philosophy is to make simple things simple (don''t worry,
there''s still space for complex things -> descriptors, metaclasses etc).

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


Gerard Flanagan写道:
Gerard Flanagan wrote:
我有以下代码:

#### builder.py #########
类HtmlBuilder(对象):

@staticmethod
def page(title =''''):
返回HtmlPage(标题)

@staticmethod
def元素(标签,文本=无,* * attribs):
返回HtmlElement(标签,文字,** attribs)

@staticmethod
def文字(文字):
返回HtmlLiteral(文字)
I have the following code:

#### builder.py #########
class HtmlBuilder(object):

@staticmethod
def page(title=''''):
return HtmlPage(title)

@staticmethod
def element(tag, text=None, **attribs):
return HtmlElement(tag, text, **attribs)

@staticmethod
def literal(text):
return HtmlLiteral(text)




只是好奇,但是这个课程的目的是什么,以及是什么给了

你想以这种方式构建你的程序?


< / F>



just curious, but what''s the purpose of this class, and what gave
you the idea to structure your program in this way ?

</F>


bruno at modulix写道:
bruno at modulix wrote:
Gerard Flanagan写道:
Gerard Flanagan wrote:
你好

我有以下代码:

#### builder.py #########
类HtmlBuilder(对象):

@staticmethod
def page(title =''''):
返回HtmlPage(标题)

@staticmethod
def元素(tag,text = None,** attribs):
返回HtmlElement(标签,文字,** attribs)

@staticmethod
def literal(文字):
返回HtmlLiteral(文字)
Je ne voispastrès bienàquoisert cette classe(àmoinsbien s?r
qu''il y ait d''autre code)。 Pour ce que jevoislà,pourquoi ne pas
appeler directement les classes HtmlPage,HtmlElement et HtmlLiteral?
Hello

I have the following code:

#### builder.py #########
class HtmlBuilder(object):

@staticmethod
def page(title=''''):
return HtmlPage(title)

@staticmethod
def element(tag, text=None, **attribs):
return HtmlElement(tag, text, **attribs)

@staticmethod
def literal(text):
return HtmlLiteral(text)
Je ne vois pas très bien à quoi sert cette classe (à moins bien s?r
qu''il y ait d''autre code). Pour ce que je vois là, pourquoi ne pas
appeler directement les classes HtmlPage, HtmlElement et HtmlLiteral ?




C''est une vaine tentative d''贴近工厂模式 ! J''ai eu

开始''ecrire les classes''ul(HtmlElement),li(HtmlElement)等'',

et le but de'' HtmlElementFactory''etait d''eviter ceci(cela?)。 Il ya

une recette ici:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/86900


mais il利用''申请'',qui est ... blah


我试图实施工厂模式。

上面的配方使用''apply''这是根据

文档弃用,我想我很好奇如何做同样的事情

没有''apply''。
$ b $呃...我没看到这堂课的重点。为什么不直接调用
HtmlPage | Element | Literal类?



C''est une vaine tentative d''appliquer "the Factory Pattern" ! J''ai eu
commence d''ecrire les classes ''ul(HtmlElement), li(HtmlElement), etc '',
et le but de ''HtmlElementFactory'' etait d''eviter ceci (cela?). Il y a
une recette ici:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/86900

mais il utilise ''apply'', qui est...blah

I was trying to implement the factory pattern.
The recipe above uses ''apply'' which is deprecated according to the
docs, and I suppose I was curious how to do the same sort of thing
without ''apply''.
Err... I don''t see the point of this class. Why not just calling the
HtmlPage|Element|Literal classes directly ?

类HtmlElementFactory(对象):

def __init __(self):
for [''li'',''ul'']中的标签:
setattr(self,tag,HtmlBuilder.element(tag))

##### ####################

所以我可以做到以下几点:

html = HtmlElementFactory()
ul = html.ul
ul.attrib [''class''] =''默认''
我在范围内(3):
li = html.li
li.text =''ghfhj''
ul.append(li)
print ul.to_string()

但我想做的是:

html = HtmlElementFactory()
ul = html.ul(class =''default'')

class HtmlElementFactory(object):

def __init__(self):
for tag in [''li'', ''ul'']:
setattr( self, tag, HtmlBuilder.element(tag) )

#########################

and so I can do the following:

html = HtmlElementFactory()
ul = html.ul
ul.attrib[''class''] = ''default''
for i in range(3):
li = html.li
li.text = ''ghfhj''
ul.append(li)
print ul.to_string()

but what I''d like to do is:

html = HtmlElementFactory()
ul = html.ul( class=''default'' )

for i在范围(3)中:
ul.append(html.li(''ghfhj'')
print ul.to_string()
for i in range(3):
ul.append( html.li( ''ghfhj'' )
print ul.to_string()



''to_字符串''?
让我们看看'''to_string'',一个只有静态方法的类......
你是来自Java,不是吗? - )



''to_string'' ?
Let''s see... ''to_string'', a class with only staticmethods in it...
You''re coming from Java, aren''t you ?-)




我生命中从未去过Java!

我不知道我是否理解你,HtmlElement有一个'' to_string''方法

但没有静态方法:


class HtmlElement(list):


def __init __( self,tag,text = None,** attrib):

self.tag = tag

self.text = text

self.attrib = attrib


def写(自我,作家):

writer.start(self.tag,self.attrib)

如果self.text不是None:

writer.data(self.text)

for self in self:

node.write(writer )

writer.end()


def to_string(self):

out = StringIO()

writer = HtmlWriter(out)

self.write(作家)

ret = out.getvalue()

out.close( )

返回
(如果是,google forpython不是java,它可能会有所帮助)



Never been to Java in my life!
I don''t know if I understand you, HtmlElement has a ''to_string'' method
but no static methods:

class HtmlElement(list):

def __init__(self, tag, text=None, **attrib):
self.tag = tag
self.text = text
self.attrib = attrib

def write(self, writer):
writer.start(self.tag, self.attrib)
if self.text is not None:
writer.data(self.text)
for node in self:
node.write(writer)
writer.end()

def to_string(self):
out = StringIO()
writer = HtmlWriter(out)
self.write(writer)
ret = out.getvalue()
out.close()
return ret
(if yes, google for "python is not java", it may be helpful)

ie。将* args和** kwargs传递给HtmlElement构造函数。
有什么建议吗?
是的:将* args和** kwargs传递给HtmlElement构造函数! - )

ie. to pass along *args and **kwargs to the HtmlElement constructor.
Any suggestions?
yes : pass along *args and **kwargs to the HtmlElement constructor !-)

或者有更好的办法来做这种事吗?
Or is there a better way to this kind of thing?



是的:亲吻(保持简单愚蠢)

没有足够的代码来真正掌握你想要做的事情,但是从我看到的情况来看,我会说你有一个任意的过度复杂化的坏情况。



yes again : kiss (Keep It Simple Stupid)

There''s not enough code to really grasp what you''re trying to do, but
from what I see, I''d say you''re having a bad case of arbitrary
overcomplexification.




我的代码本身只是一个学习项目(etant sans emploi a ce

moment,moi-meme ......)它是毫无疑问在

分钟有点'过度',但这是第一次尝试,我可以随时重构。

有什么问题:

#nb:class是Python中的保留字
ul = HtmlElement(''ul'',css_class =''default'')
for i in range( 3):
ul.append(HtmlElement( 'li'',''baaz%d''%i)

#nb2:使用HtmlElement的__str __()方法
print str(ul)
Python的理念是让简单的事情变得简单(别担心,还有复杂事物的空间 - >描述符,元类等)。

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



My code itself is just a learning project ( etant sans emploi a ce
moment, moi-meme...) and it is no doubt a bit ''over-egged'' at the
minute, but it is a first attempt and I can always refactor later.
What''s wrong with:

# nb: class is a reserved word in Python
ul = HtmlElement(''ul'', css_class=''default'')
for i in range(3):
ul.append(HtmlElement(''li'', ''baaz%d'' % i)

# nb2: use the __str__() method of HtmlElement
print str(ul)

Python''s philosophy is to make simple things simple (don''t worry,
there''s still space for complex things -> descriptors, metaclasses etc).

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




Merci bien pour votre reponse。


Gerard



Merci bien pour votre reponse.

Gerard


这篇关于setattr问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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