How to create inline objects with properties?

后端 未结 9 732
误落风尘
误落风尘 2020-12-04 19:12

In Javascript it would be:

var newObject = { \'propertyName\' : \'propertyValue\' };
newObject.propertyName;  // retur         


        
9条回答
  •  难免孤独
    2020-12-04 19:40

    It is easy in Python to declare a class with an __init__() function that can set up the instance for you, with optional arguments. If you don't specify the arguments you get a blank instance, and if you specify some or all of the arguments you initialize the instance.

    I explained it here (my highest-rated answer to date) so I won't retype the explanation. But, if you have questions, ask and I'll answer.

    If you just want a generic object whose class doesn't really matter, you can do this:

    class Generic(object):
        pass
    
    x = Generic()
    x.foo = 1
    x.bar = 2
    x.baz = 3
    

    An obvious extension would be to add an __str__() function that prints something useful.

    This trick is nice sometimes when you want a more-convenient dictionary. I find it easier to type x.foo than x["foo"].

提交回复
热议问题