Q about assignment and references
clp2 at rebertia.com
Tue Apr 6 23:29:46 EDT 2010
On Tue, Apr 6, 2010 at 7:51 PM, jdbosmaus <jayjoeryu at yahoo.com> wrote:
> Pretty new to Python, but I thought I understood what is meant by "an
> assignment is a reference."
I recommend the effbot's treatment of the calling semantics:
...But I don't think that's the issue here.
> Until I tried to understand this.
> Here is a (fragment of an) event handler for a group of three wxPython
I believe the unintuitiveness here is due to quirks in the exact way
wxPython wraps wxWindows, not Python itself.
> def ScanModeHdlr(self, event):
> esource = event.GetEventObject() #return button that was
> fontUn = esource.Font
> fontSel = esource.Font
> fontUn.Style = wx.NORMAL
> fontSel.Style = wx.ITALIC
> fontUn.PointSize = 9
> fontSel.PointSize = 12
> btnlist = (self.TBN_NewScan, self.TBN_CheckScan,
> for x in btnlist:
> if x is esource:
> x.Font = fontSel
> x.Font = fontUn
> Now, what bothers me is that in the 3rd and 4th lines, the RHS
> "esource.Font" returns a wx.Font object that is a *copy* of the font
> object of the button.
> the for-loop we assign the font object to a LHS object that ...
> semantically, looks exactly like the thing that returned a *copy* up
> I could understand if the setting-semantics in the for-loop needed to
> be something like "x.SetFont(fontUn)", or even "x.SetFont = fontUn".
> (for "could understand" read "would be much happier.")
> I could also understand if the 3rd and 4th lines needed to look like
> "fontUn = copy(esource.Font)". (which doesn't work; "copy" doesn't
> know what to do.)
In fact, I /suspect/ (I haven't used wxPython, so I can't be sure)
both of what you describe is /exactly/ what's going on here. wxPython
is /probably/ invoking the magic of properties
(http://docs.python.org/library/functions.html#property) to make
`esource.Font` return a copy and turn `esource.Font = fontUn` into a
setter method call behind the scenes.
> What I can't understand is how the semantics that actually works makes
> sense in terms of Python's assignment conventions.
Read about property() [see above link] and be enlightened. It
basically lets accesses and assignments to an attribute trigger method
calls; alternately, and probably more intuitively, you can look at it
as allowing a getter-setter pair to be presented (syntactically) like
a vanilla attribute.
Hence, esource.Font /looks/ like an attribute, but doesn't quack
[behave] like a normal one.
More information about the Python-list