空类作为c结构? [英] empty classes as c structs?

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

问题描述

我发现自己经常做以下事情:


class Struct:

pass

....

blah = Struct()

blah.some_field = x

blah.other_field = y

....


有更好的方法吗?这被认为是不好的编程

练习?我不喜欢使用元组(或列表),因为我宁愿使用

符号名称,而不是数字下标。另外,我不想每次想要这样做时都会声明空的Struct类(通常是

)。


反馈表示赞赏,谢谢。

解决方案

Christopher J. Bottaro写道:

我发现自己经常做以下事情:

类结构:
传递
...
blah = Struct()
blah.some_field = x
blah.other_field = y
...

有没有更好的方法呢?




是的 - 帮助我集结我的通用对象PEP,它为Python标准库提出了一个类型(可能是要重命名)的类型。 =)使用这个

类型,您可以将代码编写为:


blah = Bunch()

blah.some_field = x

blah.other_field = y


或简单地说:


blah = Bunch(some_field = x,other_field = y)


我在2005年1月2日申请了PEP号码,但还没有收到回复。

但是,你可以看到最近的草案PEP的内容:

http://mail.python.org/pipermail/pyt...ry/262201.html


你可以看到补丁的第一个版本at:

http://sourceforge.net/tracker/?func...&group_id=5470


版本的Python,假设它'接受了,

Bunch类的当前代码如下。


STeVe


--- -------------------------------------------------- -----------------

#Copyright(c)2004 Python Software Foundation。

#保留所有权利。 />

#作者:Steven Bethard< steven.bethard at gmail.com>


导入运算符为_operator


class Bunch(object):

""" Bunch([bunch | dict | seq],** kwds) - >新的束指定

属性


新的Bunch对象的属性初始化自(如果提供

)另一个从对象关系参数列表中的

name = value对中绑定对象的属性,

字典或一系列(名称,值)对。


示例用法:

Bunch(eggs = 1,spam = 2,ham = 3)
束(鸡蛋= 1,火腿= 3,垃圾邮件= 2)束({''egg'':1,''spam'':2,''ham'':3})
群(鸡蛋= 1,火腿= 3,垃圾邮件= 2)群([('''鸡蛋'',1),(''垃圾'',2),(''火腿'',3)] )
群(鸡蛋= 1,火腿= 3,垃圾邮件= 2)群(群(鸡蛋= 1,垃圾邮件= 2),火腿= 3)



群(鸡蛋= 1,火腿= 3,垃圾邮件= 2)

"""


def __init __(* args,** kwds):

""" Initializes a Bunch instance。"""

Bunch.update(* args,** kwds)


def __eq __(自我,其他):

"" ;" x .__ eq __(y)< ==> x == y


如果两个对象具有相同的

属性且每个属性的值相同,则认为它们是相等的。

"""

return(其他.__ class__ == self .__ class__和

self .__ dict__ == other .__ dict__)


def __repr __(self):

""" x .__ repr __()< ==> repr(x)


如果这一堆中的所有属性值(以及任何嵌套的

束)都可以使用eval(repr(x))重现,那么一堆

对象也可以再现为eval(repr(x))。

""

return''%s( %s)''%(self .__ class __.__ name __,

'',''。join(''%s =%r''%(k,v)

代表k,v

in self .__ dict __。items()))


@staticmethod

def update(* args,** kwargs):

""" update(bunch,[bunch | dict | seq,] ** kwargs) - >没有


更新第一个Bunch对象的属性(如果提供了

)另一个Bunch对象的属性,一个

字典,或一系列(名称,值)对,然后来自

关键字参数列表中的名称=值对。

""" ;

如果不是1< = len(args)< = 2:

引发TypeError(''预期的1或2个参数,得到%i''%

len(args))

self = args [0]

如果不是isinstance(self,Bunch):

引发TypeError(''更新的第一个参数应该是Bunch,''

''不是%s''%type(self).__ name__)

if len( args)== 2:

other = args [1]

if isinstance(other,Bunch):

other = other .__ dict __

尝试:

self .__ dict __。update(其他)

除外(TypeError,ValueError):

引发TypeError (''不能用%s更新束''%

类型(其他).__ name__)

self .__ dict __。update(kwargs)


Christopher,


我发现自己做了同样的事情。你可以这样做:


blah = type(''Struct'',(),{})()

blah.some_field = x


我想如果我需要在运行时构建对象我只会这样做

基于我在编译时没有的信息,因为你的空课程的两行代码可能更容易识别

给更多人。


如果这样使用类型()打击任何人不合适请让我

知道,因为我真的不知道。 :)


Christopher J. Bottaro写道:

我发现自己经常做以下事情:

类结构:
传递
...
blah =结构()
blah.some_field = x
blah.other_field = y
...
符号名称,而不是数字下标。另外,我不想每次想要这样做时都声明空的Struct类(经常是这样)。

感谢您的反馈意见。



Christopher J. Bottaro写道:

我发现自己经常做以下事情:

class Struct:
传递
...
blah = Struct()
blah.some_field = x
blah.other_field = y
......

有更好的方法吗?这被认为是不好的编程实践吗?我不喜欢使用元组(或列表),因为我宁愿使用
符号名称,而不是数字下标。另外,我不想每次想要这样做时都声明空的Struct类(这经常是
)。




我有一个我自己的模块(data.py),我经常使用它。它包含:


类数据(对象):

def __init __(self,** initial):

的名称, val在initial.iteritems():

setattr(self,name,val)


def __repr __(自我):

names =已排序([名称在dir(自我)中的名称

,如果不是name.startswith(''_'')],

key = lambda name :( name .lower(),name))

返回''%s(%s)''%(self .__ class __.__ name __,'',''。join([

''%s =%r''%(nm,getattr(self,nm))为名称中的nm]))


优点是我可以看到值在Data对象中只需打印对象即可获得
。我用它如下:

来自数据导入的
数据


blah =数据(some_field = 3,other_field = 13)

...

blah.other_field = 23

...


- 斯科特David Daniels Sc***********@Acm.Org


I find myself doing the following very often:

class Struct:
pass
....
blah = Struct()
blah.some_field = x
blah.other_field = y
....

Is there a better way to do this? Is this considered bad programming
practice? I don''t like using tuples (or lists) because I''d rather use
symbolic names, rather than numeric subscripts. Also, I don''t like having
to declare the empty Struct class everytime I want to do this (which is
very often).

Feedback is appreciated, thanks.

解决方案

Christopher J. Bottaro wrote:

I find myself doing the following very often:

class Struct:
pass
...
blah = Struct()
blah.some_field = x
blah.other_field = y
...

Is there a better way to do this?



Yes -- help me rally behind my generic object PEP which proposes a Bunch
type (probably to be renamed) for the Python standard lib. =) With this
type, you could write your code as:

blah = Bunch()
blah.some_field = x
blah.other_field = y

or simply:

blah = Bunch(some_field=x, other_field=y)

I requested a PEP number on 2 Jan 2005, but haven''t heard back yet.
However, you can see a recent draft of the PEP at:

http://mail.python.org/pipermail/pyt...ry/262201.html

and you can see the first version of the patch at:

http://sourceforge.net/tracker/?func...&group_id=5470

If you''d like to use the Bunch type now (instead of waiting for a future
version of Python, assuming it''s accepted), the current code for the
Bunch class follows.

STeVe

----------------------------------------------------------------------
# Copyright (c) 2004 Python Software Foundation.
# All rights reserved.

# Written by Steven Bethard <steven.bethard at gmail.com>

import operator as _operator

class Bunch(object):
"""Bunch([bunch|dict|seq], **kwds) -> new bunch with specified
attributes

The new Bunch object''s attributes are initialized from (if
provided) either another Bunch object''s attributes, a
dictionary, or a sequence of (name, value) pairs, then from the
name=value pairs in the keyword argument list.

Example Usage:

Bunch(eggs=1, spam=2, ham=3) Bunch(eggs=1, ham=3, spam=2) Bunch({''eggs'':1, ''spam'':2, ''ham'':3}) Bunch(eggs=1, ham=3, spam=2) Bunch([(''eggs'',1), (''spam'',2), (''ham'',3)]) Bunch(eggs=1, ham=3, spam=2) Bunch(Bunch(eggs=1, spam=2), ham=3)


Bunch(eggs=1, ham=3, spam=2)
"""

def __init__(*args, **kwds):
"""Initializes a Bunch instance."""
Bunch.update(*args, **kwds)

def __eq__(self, other):
"""x.__eq__(y) <==> x == y

Two Bunch objects are considered equal if they have the same
attributes and the same values for each of those attributes.
"""
return (other.__class__ == self.__class__ and
self.__dict__ == other.__dict__)

def __repr__(self):
"""x.__repr__() <==> repr(x)

If all attribute values in this bunch (and any nested
bunches) are reproducable with eval(repr(x)), then the Bunch
object is also reproducable for eval(repr(x)).
"""
return ''%s(%s)'' % (self.__class__.__name__,
'', ''.join(''%s=%r'' % (k, v)
for k, v
in self.__dict__.items()))

@staticmethod
def update(*args, **kwargs):
"""update(bunch, [bunch|dict|seq,] **kwargs) -> None

Updates the first Bunch object''s attributes from (if
provided) either another Bunch object''s attributes, a
dictionary, or a sequence of (name, value) pairs, then from
the name=value pairs in the keyword argument list.
"""
if not 1 <= len(args) <= 2:
raise TypeError(''expected 1 or 2 arguments, got %i'' %
len(args))
self = args[0]
if not isinstance(self, Bunch):
raise TypeError(''first argument to update should be Bunch, ''
''not %s'' % type(self).__name__)
if len(args) == 2:
other = args[1]
if isinstance(other, Bunch):
other = other.__dict__
try:
self.__dict__.update(other)
except (TypeError, ValueError):
raise TypeError(''cannot update Bunch with %s'' %
type(other).__name__)
self.__dict__.update(kwargs)


Christopher,

I''ve found myself doing the same thing. You could do something like this:

blah = type(''Struct'', (), {})()
blah.some_field = x

I think I''d only do this if I needed to construct objects at runtime
based on information that I don''t have at compile time, since the two
lines of code for your empty class would probably be more recognizable
to more people.

If this usage of type() strikes anyone as inappropriate please let me
know, because I really don''t know. :)

Christopher J. Bottaro wrote:

I find myself doing the following very often:

class Struct:
pass
...
blah = Struct()
blah.some_field = x
blah.other_field = y
...

Is there a better way to do this? Is this considered bad programming
practice? I don''t like using tuples (or lists) because I''d rather use
symbolic names, rather than numeric subscripts. Also, I don''t like having
to declare the empty Struct class everytime I want to do this (which is
very often).

Feedback is appreciated, thanks.



Christopher J. Bottaro wrote:

I find myself doing the following very often:

class Struct:
pass
...
blah = Struct()
blah.some_field = x
blah.other_field = y
...

Is there a better way to do this? Is this considered bad programming
practice? I don''t like using tuples (or lists) because I''d rather use
symbolic names, rather than numeric subscripts. Also, I don''t like having
to declare the empty Struct class everytime I want to do this (which is
very often).



I have a module of my own (data.py) that I use a lot. It contains:

class Data(object):
def __init__(self, **initial):
for name, val in initial.iteritems():
setattr(self, name, val)

def __repr__(self):
names = sorted([name for name in dir(self)
if not name.startswith(''_'')],
key=lambda name: (name.lower(), name))
return ''%s(%s)'' % (self.__class__.__name__, '', ''.join([
''%s=%r'' % (nm, getattr(self, nm)) for nm in names]))

The advantage is that I can see the value in the Data object simply
by printing the object. I use it like:

from data import Data

blah = Data(some_field=3, other_field=13)
...
blah.other_field = 23
...

--Scott David Daniels
Sc***********@Acm.Org


这篇关于空类作为c结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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