Distinguishing attribute name from varible name to make codes clear and definite

Ben Finney ben+python at benfinney.id.au
Thu Aug 21 16:52:18 EDT 2014


luofeiyu <elearn2014 at gmail.com> writes:

> I feel that self.x and x will be confused in the following codes.

I don't see how. The examples you give have the two quite distinct in
every case.

>     exam=MyDescriptor("hallo")
>
> when class MyDescriptor  initiate , the `hallo` was passed into x in
> __init__(self, x);

That's correct; the argument ‘"hallo"’ (a text string) is the second
argument in the ‘__init__’ call, and the name ‘x’ is bound to that
value while the function executes.

> Literally  self.x maybe understood to be self.hallo ,assign a
> attribute named 'hallo' to instance exam.

No, the attribute ‘self.x’ is not to be understood as ‘self.hallo’. The
value is not the name.

If the value of the argument were 7.03, the attribute would not be named
‘self.7.03’, it would still be named ‘self.x’.

> There is a attribute y  in instance exam , the `hallo` was passed into
> x in __init__(self, x).No any relation between x and y ,`hallo` and y.
> My view is correct or not ?

You are correct that, if you were to name the attribute differently from
the parameter, there would no longer be any clear relationship.

You are, IMO, incorrect that this would help. Rather, the loss of the
clear relationship would make it much more difficult to see why the
relationship exists, and why different names were chosen.

Instead, the programmer is expected to understand that a value is
distinct from any name which is bound to that value.

-- 
 \          “Our products just aren't engineered for security.” —Brian |
  `\             Valentine, senior vice-president of Microsoft Windows |
_o__)                                                development, 2002 |
Ben Finney




More information about the Python-list mailing list