V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wellsc
V2EX  ›  Python

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

  •  
  •   wellsc ·
    WyattJia · 2018-05-03 17:07:06 +08:00 · 1636 次点击
    这是一个创建于 2156 天前的主题,其中的信息可能已经有所发展或是发生改变。
    不知道应该答 class method instance method 相关的知识,还是内存管理或 __slots__ 相关的知识...
    ilucio
        1
    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
        2
    wellsc  
    OP
       2018-05-04 15:00:01 +08:00
    @ilucio #1 我跟面试官确认过的,他说的对象是指类的实例,对象的方法是指 实例的 methods,刚开始我也答的是 __dict__ ,但是他说 dict 只是把对象属性返回出来了,而没有说清楚对象方法是怎么存储的。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   971 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 20:22 · PVG 04:22 · LAX 13:22 · JFK 16:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.