Python:Python函数是否等同于Python对象?

时间:2014-03-09 12:03:52

标签: python

我正在尝试使用Python,并尝试了一个示例,但它确实有效。

def foo():
    print 'hello world'

foo.a = True

所以它看起来我foo是一个对象,虽然它看起来像一个函数。 它的技术术语是什么,它的用例是什么?

3 个答案:

答案 0 :(得分:1)

Everything is an object。至少几乎一切。 Python中很少有东西你无法创建属性。可能只有一些在C中实现并作为Python对象公开的东西,因为它们可能不支持必要的接口。例如,您无法在int类型的对象内创建属性,因为它没有属性字典(主要是出于性能原因,我想)。但它仍然是一个对象,但功能有限。

答案 1 :(得分:0)

是的,Python中的函数就是其他所有对象:

Python 3.3.2+ (default, Oct  9 2013, 14:50:09) 
>>> def a(): pass
... 
>>> type(a)
<class 'function'>
>>> import types
>>> types.FunctionType
<class 'function'>
>>> type(a) is types.FunctionType
True
>>> 

答案 2 :(得分:0)

在Python 3中,继承层次结构牢牢扎根于object,但在Python 2中,事情并不那么明确。虽然两个版本的确都是“一切都是对象”,但真正的问题是“什么类型的对象”?

所以这是一个程序,在两个版本下运行是有益的(我希望)。

class OldStyle:
    pass

class NewStyle(object):
    pass

old_obj = OldStyle()
new_obj = NewStyle()

print(OldStyle, NewStyle)
print(old_obj, new_obj)

为了更容易看到发生了什么,我只是将程序粘贴到不同的解释器中,输出如下所示。

airhead:project sholden$ python2
Python 2.7.6 (default, Nov 19 2013, 03:12:29)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class OldStyle:
...     pass
...
>>> class NewStyle(object):
...     pass
...
>>> old_obj = OldStyle()
>>> new_obj = NewStyle()
>>>
>>> print(OldStyle, type(OldStyle))
(<class __main__.OldStyle at 0x105345808>, <type 'classobj'>)
>>> print(NewStyle, type(NewStyle))
(<class '__main__.NewStyle'>, <type 'type'>)
>>> print(old_obj, type(old_obj))
(<__main__.OldStyle instance at 0x10535ff38>, <type 'instance'>)
>>> print(new_obj, type(new_obj))
(<__main__.NewStyle object at 0x105360bd0>, <class '__main__.NewStyle'>)
>>>

对战

airhead:project sholden$ python3
Python 3.3.2 (default, Nov 19 2013, 03:15:33)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class OldStyle:
...     pass
...
>>> class NewStyle(object):
...     pass
...
>>> old_obj = OldStyle()
>>> new_obj = NewStyle()
>>>
>>> print(OldStyle, type(OldStyle))
<class '__main__.OldStyle'> <class 'type'>
>>> print(NewStyle, type(NewStyle))
<class '__main__.NewStyle'> <class 'type'>
>>> print(old_obj, type(old_obj))
<__main__.OldStyle object at 0x106884c90> <class '__main__.OldStyle'>
>>> print(new_obj, type(new_obj))
<__main__.NewStyle object at 0x106884c50> <class '__main__.NewStyle'>
>>>

你会发现两个输出之间实际上相对较少的显着差异,这是Guido van Rossum作为语言设计师的功劳,因为在2.2版本发布时发生了重大偏离。

关注细节,在Python 2.x中,不从object继承的类是classobj类型,其实例将是类型(实例)。但是,在Python 3.x中,类的类型为type,实例的类型为__main__.NewStyle

在这两个版本中,我认为没有对象x,表达式isinstance(object, x)的计算结果为False。