new-style class instance check
Robert Brewer
fumanchu at amor.org
Sat Apr 10 20:22:40 EDT 2004
Richard Gruet wrote:
> Robert
>
> Thank you for your suggestion.
> But unfortunately, isNewStyleClassInstance(o) must return False for
> *everything but* an instance of a new-style class. If o is
> e.g. a function:
> def foo(): pass
> foo.__class__.rmo
> <built-in method mro of type object at 0x1E0BA9E0>
>
> so isNewStyleClassInstance(foo) would return True !
Yes, function() is new-style. So is int. I think what you're asking for
is not whether a given object is new-style or not, but whether it is a
*user-defined* new-style object (correct me if I'm wrong). The problem
with that approach occurs with, e.g.:
class RangedInt(int):
def __init__(self, value, lower, upper):
int.__init__(self, value)
self.lower = lower
self.upper = upper
Now, since int() creates new-style objects, should RangedInt pass your
test or not? If not, then you could simply check the mro to see that
there are only two values: the target class and "object":
>>> class C(object): pass
...
>>> C.mro()
[<class '__main__.C'>, <type 'object'>]
...but if you want RangedInt(3) to pass when int(3) doesn't, you've got
more inspection to do:
>>> RangedInt.mro()
[<class '__main__.RangedInt'>, <type 'int'>, <type 'object'>]
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list