RBuntu RBuntu - 4 months ago 12
Python Question

Is there a way to create and name an object/class, as well as run a method of the class in the same line?

I am just trying to clean up some code and I was wondering if there is a way to create a new named object as well as run a method in the objects class in the same line. For example:

self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white")
self.equipment_widgets["NumOfStagesLabelCentComp"].place(relx=0.5, y=260, anchor="center")

In the first line, I am initializing a new
class as an object in a dictionary called
. In the next line, I use the
method to place the label object in my GUI.

If I put
at the end of the first line instead, a
object is created.


You need to design your class methods to be chainable, which means that all methods that just modify the object (as opposed to returning information from the object) should end with return self. This allows you to write:


If the place() method is designed this way, you should be able to use it on the first line.

self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white").place(relx=0.5, y=260, anchor="center")

Note that most mutating methods in Python's standard classes are not chainable, they typically return None. So this type of programming is not very pythonic.