[英]Python. Memory overhead of having many methods in a base class.
I am developing a user-centric front for an existing datastore. 我正在为现有数据存储开发以用户为中心的前端。
Rather than having cumbersome lookup tables in my UI, I have attached UI "hints" to many of my data wrappers. 我没有在UI中添加繁琐的查找表,而是将UI“提示”附加到了许多数据包装器上。
For instance: 例如:
class LibraryBook(IDatabaseItem):
"""There are a billion books in my library"""
@property
def name_hint(self):
"""This is a METHOD, I do not want to duplicate the fields in a new string!"""
return self.author + " " + self.title
@staticmethod
@property
def type_name_hint():
"""This is CONSTANT, there is no point in every instance having an attribute!"""
return "Book"
. . .
(The interface IDatabaseItem
is just to make code-completion from an IDE easier, I understand it isn't necessary in Python). (接口IDatabaseItem
只是为了使来自IDE的代码完成更容易,我知道在Python中这不是必需的)。
My concern is that all of these small methods are creating memory overhead. 我担心的是,所有这些小的方法都在增加内存开销。 C++ would create a simple pointer to a v-table, but from what I have read Python uses a dict
, does this incur a massive memory overhead, not to mention having a dict-lookup to access otherwise trivial functions - for instance type_name_hint
above is essentially const . C ++会创建一个指向v表的简单指针,但是据我所读的Python使用dict
,这样做会导致大量的内存开销,更不用说通过dict查找来访问其他微不足道的功能了-例如上面的type_name_hint
是本质上是const 。
So my question is: Is there a memory overhead, what is the better way if so, or how does Python resolve the issue if not. 所以我的问题是:是否有内存开销?如果有,哪种更好的方法?如果没有,Python如何解决该问题?
Python class instances are basically a dict of instance variables, plus a reference to the class itself. Python类实例基本上是实例变量的字典,加上对类本身的引用。 Methods defined in the class do not affect the instance size AT ALL: they are found indirectly through the class reference. 类中定义的方法不会影响实例大小AT ALL:可以通过类引用间接找到它们。 Basically, any attribute is looked up first in the instance's dict, then the class's dict, then the superclass's dict, and so on up the inheritance chain. 基本上,首先在实例的dict中查找任何属性,然后在类的dict中查找,然后在超类的dict中查找,依次类推到继承链。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.