[Tutor] New-style classes

Kent Johnson kent37 at tds.net
Thu Sep 29 15:21:54 CEST 2005


Jan Eden wrote:
> My actual code looks like this:
> 
> class Base:
>     def GetOwnType(self):
>         try: return self._own_type
>         except: return self.child_type
>     
>     def SetOwnType(self, value):
>         self._own_type = value
>         
>     own_type = property(GetOwnType, SetOwnType)
> 
> For some of the subclasses of Base, the attribute own_type is
> defined, the others should use child_type.
> 
> For both groups of subclasses, this works fine - if own_type has not
> been set somewhere else, self.child_type is returned when calling
> self.own_type.
> 
> When checking Data.Base.__mro__, I get an error, so it is not a
> new-style class by itself.
> 
> On the other hand, every time I use the own_type attribute, I do so
> via instances of new-style classes (Show.Page, Show.Author etc).

That is the key

> 
> Could it be that the nature of these classes makes the code in
> Data.Base behave according to the new-style rules?> 

Yes, I tried to show that in my example. Any class that has a new-style class as one of its base classes will be a new-style class. The attribute lookup is implemented in the metaclass.

For an instance of Data.Base, the metaclass (the class of its class) is types.ClassType, which implements old-style attribute access. So if you create a Data.Base directly the property access will be broken.

On the other hand if you create an instance of Show.Page, the meta class is type, which implements new-style attribute access and the properties will behave correctly.

You have to keep in mind, this is Python, everything is dynamic. When you define Data.Base you don't define its behaviour irrevocably. Attribute lookup happens at runtime and is affected by the current state of the object.

Kent

> Thanks,
> 
> Jan



More information about the Tutor mailing list