问个问题,面试官问你 “ Python 的对象方法是怎么存储的”,该怎么回答

2018-05-03 17:07:06 +08:00
 wellsc
不知道应该答 class method instance method 相关的知识,还是内存管理或 __slots__ 相关的知识...
1646 次点击
所在节点    Python
2 条回复
ilucio
2018-05-04 14:54:08 +08:00
感觉问的应该是类的知识。在类里定义一个方法,会在堆上开辟内存生成一个函数对象,并把这个对象名放在类的__dict__中。

class apple(object):

def price (self):
print '2'

def weight (self):
print '400g'

print apple.__dict__

{'__module__': '__main__', 'weight': <function weight at 0x03868DB0>, 'price': <function price at 0x03868D70>, '__dict__': <attribute '__dict__' of 'apple' objects>, '__weakref__': <attribute '__weakref__' of 'apple' objects>, '__doc__': None}

可见方法 price 和 weight 分别在堆上的不同位置。
wellsc
2018-05-04 15:00:01 +08:00
@ilucio #1 我跟面试官确认过的,他说的对象是指类的实例,对象的方法是指 实例的 methods,刚开始我也答的是 __dict__ ,但是他说 dict 只是把对象属性返回出来了,而没有说清楚对象方法是怎么存储的。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/451821

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX