1

This Problem is more an aesthetic thingy. But is there a handy way to create Objects in Python which act like Objects in JavaScript? In JS we simply can create an Object by saying let obj = {x,y}; and we can access it easily via obj.x.

Currently i just create a Class for it (in Python), but its so much code for such a small task, is there any small tip to replicate the same thing from JS in Python, where i can create this Object-Structure easily and call it for example via obj.attribute?

I know you can create Dictionaries as well, but then you cant call it via dict.attribute but only via dict['attribute'], and as i said its more an aesthetic thing. But also i cant create this dictionary as fast as i could in JS.

Lets say i have 3 vars: x = 0 y = 1 z = 2 and i wanna save it in an Object in JS. I would just write let myObject = {x,y,z} and i get an Object back with the structure:

myObject = {
  x: 1,
  y: 2,
  z: 3
};

and i can call it easily. But in Python i need to say:

myDict = {
  "x": 1,
  "y": 2,
  "z": 3
}

and i cant call it easily.

So summed up:

Is there anything in Python similar to that in JS i mentioned above?

Appreciate any comment, not the best in Python so i am missing a lot of things probably :)

Raqha
  • 754
  • 4
  • 17
  • 2
    Not really. They're very different languages. – Barmar Oct 22 '20 at 19:16
  • 1
    I agree that JS is more elegant when it comes to objects. Python classes and `namedtuple`s support dot notation but they're apples and oranges and ultimately you have to embrace Python. There is syntax like `dict(foo="bar", baz="quux")` though. – ggorlen Oct 22 '20 at 19:19
  • Yes it’s possible, but look out for gotchas like trying to use a Python keyword like `for`, `whiel`, etc. as an attribute name which will give an error. – DisappointedByUnaccountableMod Oct 22 '20 at 19:32

0 Answers0