Sc***********@Acm.Org I find myself doing the following very often:class Struct:pass....blah = Struct()blah.some_field = xblah.other_field = y....Is there a better way to do this? Is this considered bad programmingpractice? I don''t like using tuples (or lists) because I''d rather usesymbolic names, rather than numeric subscripts. Also, I don''t like havingto declare the empty Struct class everytime I want to do this (which isvery often).Feedback is appreciated, thanks. 解决方案Yes -- help me rally behind my generic object PEP which proposes a Bunchtype (probably to be renamed) for the Python standard lib. =) With thistype, you could write your code as:blah = Bunch()blah.some_field = xblah.other_field = yor 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.htmland you can see the first version of the patch at: http://sourceforge.net/tracker/?func...&group_id=5470If you''d like to use the Bunch type now (instead of waiting for a futureversion of Python, assuming it''s accepted), the current code for theBunch class follows.STeVe----------------------------------------------------------------------# Copyright (c) 2004 Python Software Foundation.# All rights reserved.# Written by Steven Bethard <steven.bethard at gmail.com>import operator as _operatorclass Bunch(object):"""Bunch([bunch|dict|seq], **kwds) -> new bunch with specifiedattributesThe new Bunch object''s attributes are initialized from (ifprovided) either another Bunch object''s attributes, adictionary, or a sequence of (name, value) pairs, then from thename=value pairs in the keyword argument list.Example Usage: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 == yTwo Bunch objects are considered equal if they have the sameattributes and the same values for each of those attributes."""return (other.__class__ == self.__class__ andself.__dict__ == other.__dict__)def __repr__(self):"""x.__repr__() <==> repr(x)If all attribute values in this bunch (and any nestedbunches) are reproducable with eval(repr(x)), then the Bunchobject is also reproducable for eval(repr(x))."""return ''%s(%s)'' % (self.__class__.__name__,'', ''.join(''%s=%r'' % (k, v)for k, vin self.__dict__.items()))@staticmethoddef update(*args, **kwargs):"""update(bunch, [bunch|dict|seq,] **kwargs) -> NoneUpdates the first Bunch object''s attributes from (ifprovided) either another Bunch object''s attributes, adictionary, or a sequence of (name, value) pairs, then fromthe 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)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 simplyby printing the object. I use it like:from data import Datablah = Data(some_field=3, other_field=13)...blah.other_field = 23...--Scott David Daniels Sc***********@Acm.Org 这篇关于空类作为c结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-15 05:06