Re: [Tutor] New-style classes
by Kent Johnson other posts by this author
Sep 29 2005 6:22AM messages near this date
Re: [Tutor] New-style classes
|
[Tutor] Flattening multi-dimentional list
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, whi
ch 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 impl
ements 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 y
ou don't define its behaviour irrevocably. Attribute lookup happens at runtime and is affect
ed by the current state of the object.
Kent
> Thanks,
>
> Jan
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Jan Eden
Kent Johnson
Jan Eden
Kent Johnson
|