为什么对实例方法的引用存储在每个实例对象中,而不是存储在类对象中? [英] Why are references to instance methods stored in each instance object rather than in the class object?

查看:100
本文介绍了为什么对实例方法的引用存储在每个实例对象中,而不是存储在类对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,类的每个实例都存储对实例方法的引用.

From what I understand, each instance of a class stores references to the instance's methods.

我认为,从概念上讲,一个类的所有实例都具有相同的实例方法.如果是这样,那么节省内存和逻辑清晰性似乎都表明实例方法应该存储在类对象中,而不是实例对象中(实例对象在类对象中查找它们;当然,每个实例都有对其实例的引用.班级).为什么不这样做?

I thought, in concept, all instances of a class have the same instance methods. If so, both memory savings and logical clarity seem to suggest that instance methods should be stored in the class object rather than the instance object (with the instance object looking them up through the class object; of course, each instance has a reference to its class). Why is this not done?

第二个问题.为什么不能以类似于实例属性的方式(即通过__dict__或通过某些其他系统属性)访问实例方法?有什么方法可以查看(并可能更改)名称和实例方法的引用吗?

A secondary question. Why are instance methods not accessible in a way similar to instance attributes, i.e., through __dict__, or through some other system attribute? Is there any way to look at (and perhaps change) the names and the references to instance methods?

糟糕,抱歉.我完全错了.我看到了以下Python 2代码,并从中错误地得出结论,实例方法存储在实例中.我不确定它会做什么,因为我不使用Python 2,并且new从Python 3中消失了.

Oops, sorry. I was totally wrong. I saw the following Python 2 code, and incorrectly concluded from it that instance methods are stored in the instances. I am not sure what it does, since I don't use Python 2, and new is gone from Python 3.

import new
class X(object):
  def f(self):
    print 'f'
a = X()
b = X()
def g(self):
  print 'g'
# I thought this modified instance method just in a, not in b
X.f = new.instancemethod(g, a, X)

推荐答案

据我了解,类的每个实例都存储对实例方法的引用.

From what I understand, each instance of a class stores references to the instance's methods.

我不知道你从哪里得到的,但这是错误的.他们没有.

I don't know where you got this from, but it's wrong. They don't.

为什么不能以类似于实例属性的方式(即通过__dict__或通过某些其他系统属性)访问实例方法?

Why are instance methods not accessible in a way similar to instance attributes, i.e., through __dict__, or through some other system attribute?

好吧,因为它们没有存储在实例上.

Well, because they are not stored on the instance.

有没有办法查看(也许更改)名称和实例方法的引用?

Is there any way to look at (and perhaps change) the names and the references to instance methods?

由于这些引用不存在,因此无法更改它们.您当然可以通过常规分配来创建所需的任何属性,但是请注意,实例上存储的函数不会像普通方法那样对待-隐式传递self参数的机制不适用于它们.

Since these references don't exist, you cannot change them. You can of course create any attribute you want by normal assignments, but note that functions stored on the instance are not treated like ordinary methods -- the mechanism that implicitly passes the self parameter does not apply for them.

这篇关于为什么对实例方法的引用存储在每个实例对象中,而不是存储在类对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆