开发者

How to tell python non-class objects from class objects

I am new to python. I think non-class objects do not have bases attribute whereas class objects do have it. But I am not sure. How does python\cpython checks if an object is non-class or class and passes the correct arguments to the object's descriptor attribute accordingly during the attribute access?

============================================

updated:

I was learning how __getattribute__ and descriptor cooperate together to make bounded methods. I was wondering how class object & non-class object invokes the descriptor's __get__ differently. I thought those 2 types of objects shared the same __getattribute__ CPython function and that same function would have to know if the invoking object was a class or non-class. But I was wrong. This article explains it well:

http://docs.python.org/dev/howto/descriptor.html#functions-and-methods

So class object use type.__getattribute__ whereas non-class object use object.__getattribute__. They are different CPython functions. And super has a third __getattribute__ CPython implementation as well.

However, about the super one, the above article states th开发者_Go百科at: quote and quote


The object returned by super() also has a custom _getattribute_() method for invoking descriptors. The call super(B, obj).m() searches obj._class_._mro_ for the base class A immediately following B and then returns A._dict_['m']._get_(obj, A). If not a descriptor, m is returned unchanged. If not in the dictionary, m reverts to a search using object._getattribute_().


The statement above didn't seem to match my experiment with Python3.1. What I saw is, which is reasonable to me:

super(B, obj).m ---> A.__dict__['m'].__get__(obj, type(obj))

objclass = type(obj)

super(B, objclass).m ---> A.__dict__['m'].__get__(None, objclass)

A was never passed to __get__

It is reasonable to me because I believe objclass (rather than A) 's mro chain is the one needed within m especially for the second case.

Was I doing something wrong? Or I didn't understand it correctly?


As the commenters asked: Why do you care? Usually that's a sign of not using Python the way it was meant to be used.

A very powerful concept of Python is duck typing. You don't care about the type or class of an object as long as it exposes the attributes you need.


how about inspect.isclass(objectname)?

more info here: http://docs.python.org/library/inspect.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜