代码之家  ›  专栏  ›  技术社区  ›  ShinNoNoir

对象文字是python的吗?

  •  36
  • ShinNoNoir  · 技术社区  · 14 年前

    var p = {
      name: "John Smith",
      age:  23
    }
    

    NET有匿名类型,例如。

    var p = new { Name = "John Smith", Age = 23}; // C#
    

    在Python中,可以通过(ab)使用命名参数来模拟类似的情况:

    class literal(object):
        def __init__(self, **kwargs):
            for (k,v) in kwargs.iteritems():
                self.__setattr__(k, v)
        def __repr__(self):
            return 'literal(%s)' % ', '.join('%s = %r' % i for i in sorted(self.__dict__.iteritems()))
        def __str__(self):
            return repr(self)
    

    用法:

    p = literal(name = "John Smith", age = 23)
    print p       # prints: literal(age = 23, name = 'John Smith')
    print p.name  # prints: John Smith
    

    7 回复  |  直到 14 年前
        1
  •  43
  •   Bob Stein    7 年前

    你考虑过使用 named tuple ?

    >>> from collections import namedtuple
    >>> L = namedtuple('literal', 'name age')(**{'name': 'John Smith', 'age': 23})
    

    或关键字参数

    >>> L = namedtuple('literal', 'name age')(name='John Smith', age=23)
    >>> L
    literal(name='John Smith', age=23)
    >>> L.name
    'John Smith'
    >>> L.age
    23
    

    def literal(**kw):
        return namedtuple('literal', kw)(**kw)
    

    lambda等价物是

    literal = lambda **kw: namedtuple('literal', kw)(**kw)
    

        2
  •  70
  •   Wayne Werner    14 年前

    为什么不用字典呢?

    p = {'name': 'John Smith', 'age': 23}
    
    print p
    print p['name']
    print p['age']
    
        3
  •  12
  •   Don Kirkby    13 年前

    ActiveState :

    class Bunch:
        def __init__(self, **kwds):
            self.__dict__.update(kwds)
    
    # that's it!  Now, you can create a Bunch
    # whenever you want to group a few variables:
    
    point = Bunch(datum=y, squared=y*y, coord=x)
    
    # and of course you can read/write the named
    # attributes you just created, add others, del
    # some of them, etc, etc:
    if point.squared > threshold:
        point.isok = 1
    
        4
  •  3
  •   cji    14 年前

    我认为创建“匿名”类/实例没有什么错。在一行代码中用简单的函数调用创建一个函数通常非常方便。我个人使用这样的方法:

    def make_class( *args, **attributes ):
        """With fixed inability of using 'name' and 'bases' attributes ;)"""
        if len(args) == 2:
            name, bases = args
        elif len(args) == 1:
            name, bases = args[0], (object, )
        elif not args:
            name, bases = "AnonymousClass", (object, )
        return type( name, bases, attributes )
    
    obj = make_class( something = "some value" )()
    print obj.something
    

    对于创建虚拟对象,它工作得很好。Namedtuple是可以的,但是是不可变的,这有时会带来不便。字典是。。。好吧,一本字典,但是有些情况下你必须用它来传递一些东西 __getattr__ __getitem__ .

        5
  •  2
  •   Maldus    4 年前

    types.SimpleNamespace here

    from types import SimpleNamespace
    p = SimpleNamespace(name = "John Smith", age = 23)
    print(p)
    
        6
  •  1
  •   Ken    14 年前

    Python IAQ

    从python2.3开始,您可以使用

    dict(a=1, b=2, c=3, dee=4)
    

    对我来说这已经足够了。在python2.3之前,我使用了单行函数

    def Dict(**dict): return dict
    
        7
  •  1
  •   Paul D. Waite    14 年前

    1. JavaScripts对象系统是基于原型的。JavaScript中没有类(尽管它将在将来的版本中出现)对象具有原型对象而不是类。因此,通过文本从无到有地创建对象是很自然的,因为所有对象都只需要内置根对象作为原型。在Python中,每一个对象都有一个类,您可以在有多个实例的情况下使用对象,而不仅仅是一次性的。

        8
  •  1
  •   unode    14 年前

    对于大多数情况,一本简单的词典就足够了。

    __getattr__ 功能:

    class CustomDict(dict):
        def __getattr__(self, name):
            return self[name]
    
    p = CustomDict(user='James', location='Earth')
    print p.user
    print p.location
    

    注意 :请记住,与namedtuples相反,字段不会被验证,您负责确保您的参数是正确的。参数,例如 p['def'] = 'something' p.def .