Is there a way to create and name an object/class, as well as run a method of the class in the same line?
<p>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:</p>

<pre><code>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")
</code></pre>

<p>In the first line, I am initializing a new <code>tk.Label</code> class as an object in a dictionary called <code>equipment_widgets</code>. In the next line, I use the <code>place()</code> method to place the label object in my GUI.</p>

<p>If I put <code>.place</code> at the end of the first line instead, a <code>nonetype</code> object is created.</p>

<p>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 <code>return self</code>. This allows you to write:</p>

<pre><code>object.method1(...).method2(...).method3(...)
</code></pre>

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

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

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

python python-2.7 tkinter