Create an alias to an attribute on superclass

Ben Finney ben+python at benfinney.id.au
Thu Feb 1 14:00:38 EST 2018


Sean DiZazzo <sean.dizazzo at gmail.com> writes:

> I basically just want to create an alias to an attribute on an item's
> superclass.

This description – “attribute on an item's superclass” – does not match
what you have described in the rest of the message.

Note the difference between an attribute ‘spam’ on a class ‘Lorem’
(accessed via ‘Lorem.foo’, shared among all instances of ‘Lorem’),
versus an attribute ‘spam’ on a specific instance of ‘Lorem’.

For more information, read about how Python resolves an attribute
reference from an instance, then to its class, and so on:

     A class instance has a namespace implemented as a dictionary which
     is the first place in which attribute references are searched. When
     an attribute is not found there, and the instance’s class has an
     attribute by that name, the search continues with the class attributes.

     <URL:https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy>

So, if the instance has an attribute ‘spam’, then a reference to that
name will first find the instance's attribute. If not, the class
attribute will be tried; and then that class's superclass; and so on
through the inheritance tree.

Typically, you bind an attribute on the class when you want that
reference shared (e.g. a default) for all the instances of that class;
and you bind an attribute on the instance when you want that reference
to be specific to that instance.

> So that after I create the subclass object, I can access the alias
> attribute to get the value back.

Any instance method can interrogate ‘self.spam’ to ask for that
instance's ‘spam’ attribute. This is true regardless of which class
defines that method.

What problem are you experiencing, and why do you think the default
attribute access behaviour is not enough?

-- 
 \        “Sane people have an appropriate perspective on the relative |
  `\     importance of foodstuffs and human beings. Crazy people can't |
_o__)                 tell the difference.” —Paul Z. Myers, 2010-04-18 |
Ben Finney




More information about the Python-list mailing list