Newbie: question regarding references and class relationships

Dave Angel davea at davea.name
Mon Jun 10 15:36:24 EDT 2013


On 06/10/2013 01:42 PM, Rui Maciel wrote:
> Peter Otten wrote:
>
>> Have you read the code in the interpreter session I posted?
>>
>> If you do not agree that the demonstrated behaviour is puzzling I'll have
>> to drop my claim...
>
> I don't see how it should be puzzling.  You've deleted the attribute, so it
> ceassed to exist.

Clearly you didn't reason through all the code in Peter's example.

>
>
>> Likewise if you can show a benefit of the
>>
>>>> position = []
>>
>> line.
>
> I wrote the code that way to declare intent and help document the code.  In
> this case that the class Point is expected to have an attribute named
> position which will point to a list.


So why do you also have an instance attribute of the same name?  If you 
really want all instances to have the same value for position, you'd 
better change the __init__() function so it doesn't mask that single value.

Could it be that you really meant that instances of class Point are each 
expected to have an attribute named Position?  Could it be that you want 
each instance's position to be independent of the others?

By having a class attribute with the same name as the instance 
attribute, you're occasionally going to use the class version when you 
meant the instance one.

I suspect you didn't realize the distinction between class attributes 
and instance attributes, and that a comment would be a much better way 
to communicate than creating a misleading value.

In one of your other messages, you asked:

 > How do you guarantee that any object of a class has a
 >  specific set of attributes?

Answer is to define those INSTANCE attributes in the __init__() method 
(or occasionally in the __new__() method), and to make sure you don't 
ever delete them.  The attributes of the object are instance attributes, 
while the attributes defined inside the class are class attributes.

Occasionally, it can be useful to let a class attribute be a 'backup' to 
the instance attributes, but you've got to think through your use case. 
  If memory is really tight, and if nearly all of the instances want the 
same value, then you could omit the instance attribute except for the 
exceptional ones, and let the class attribute fill in.  But as Peter 
says, if it's mutable, you then open yourself to somebody changing them 
all, thinking it was only changing the one.  But there are good reasons 
not to use this trick to save memory.


-- 
DaveA



More information about the Python-list mailing list