[Tutor] yet another question on OO inheritance

Kent Johnson kent37 at tds.net
Tue Aug 18 22:36:14 CEST 2009


On Tue, Aug 18, 2009 at 3:16 PM, Serdar Tumgoren<zstumgoren at gmail.com> wrote:
> On Tue, Aug 18, 2009 at 2:51 PM, Serdar Tumgoren<zstumgoren at gmail.com> wrote:
>> Thanks to you both for the suggestions. I think I'll try the approach
>> below. But just one follow-up: should I be setting "self.tablename",
>> or is a static attribute ("tablename") the correct approach?
>>
> Looks like it's the former (i.e. "self.tablename")

It's as I wrote it. The atttribute is created in the class definition
(not in any method) as just "tablename". This creates an attribute of
the class, rather than of the instance. It is accessed as
"self.tablename". The attribute lookup rules will look first in the
instance, fail to find 'tablename', then look in the class and find
it.

Here is a complete example:

In [1]: class Base(object):
   ...:     def show_name(self):
   ...:         print self.name

In [2]: class Derived1(Base):
   ...:     name = 'Derived1'

In [3]: class Derived2(Base):
   ...:     name = 'Derived2'

In [4]: d1 = Derived1()

In [5]: d1.show_name()
Derived1

In [6]: d2 = Derived2()

In [7]: d2.show_name()
Derived2

Kent


More information about the Tutor mailing list