Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are object literals Pythonic?

JavaScript has object literals, e.g.

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

and .NET has anonymous types, e.g.

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

Something similar can be emulated in Python by (ab)using named arguments:

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) 

Usage:

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

But is this kind of code considered to be Pythonic?

like image 884
ShinNoNoir Avatar asked Jul 26 '10 13:07

ShinNoNoir


People also ask

Is object literal same as dictionary?

it is totally not the same thing. in JS, object literals is a object, so you can combine them with data and function, and you can call the method by dot, just like x. xxx(), and you can deconstruction it with the same symbol {...}, just like other object.

What is an object literal in Python?

Objects are also called data structures. Python comes with some built-in objects. Some are used so often that Python has a quick way to make these objects, called literals. The literals include the string, unicode string, integer, float, long, list, tuple and dictionary types.

What is object literal type?

What are Object Literals? They are a comma-separated list of name-value pairs. Think of JSON Objects. Below is an Object Literal which contains the information for a user. An example of an Object Literal.


1 Answers

Why not just use a dictionary?

p = {'name': 'John Smith', 'age': 23}  print p print p['name'] print p['age'] 
like image 108
Wayne Werner Avatar answered Sep 28 '22 01:09

Wayne Werner