Python。在一个基 class 中有许多方法的内存开销。
Python. Memory overhead of having many methods in a base class.
我正在为现有数据存储开发一个以用户为中心的前台。
我没有在 UI 中进行繁琐的查找 table,而是将 UI "hints" 附加到我的许多数据包装器中。
例如:
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"
. . .
(接口 IDatabaseItem
只是为了让 IDE 的代码完成更容易,我知道在 Python 中没有必要)。
我担心的是所有这些小方法都会产生内存开销。 C++ 会创建一个指向 v-table 的简单指针,但据我所知,Python 使用 dict
,这是否会产生大量内存开销,更不用说有一个 dict-查找以访问其他微不足道的函数 - 例如上面的 type_name_hint
本质上是 const.
所以我的问题是:是否存在内存开销,如果有,更好的方法是什么,或者如果没有,Python 如何解决问题。
Python class 实例基本上是实例变量的字典,加上对 class 本身的引用。 class 中定义的方法根本不影响实例大小:它们是通过 class 引用间接找到的。基本上,首先在实例的字典中查找任何属性,然后是 class 的字典,然后是 superclass 的字典,依此类推继承链。
我正在为现有数据存储开发一个以用户为中心的前台。
我没有在 UI 中进行繁琐的查找 table,而是将 UI "hints" 附加到我的许多数据包装器中。
例如:
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"
. . .
(接口 IDatabaseItem
只是为了让 IDE 的代码完成更容易,我知道在 Python 中没有必要)。
我担心的是所有这些小方法都会产生内存开销。 C++ 会创建一个指向 v-table 的简单指针,但据我所知,Python 使用 dict
,这是否会产生大量内存开销,更不用说有一个 dict-查找以访问其他微不足道的函数 - 例如上面的 type_name_hint
本质上是 const.
所以我的问题是:是否存在内存开销,如果有,更好的方法是什么,或者如果没有,Python 如何解决问题。
Python class 实例基本上是实例变量的字典,加上对 class 本身的引用。 class 中定义的方法根本不影响实例大小:它们是通过 class 引用间接找到的。基本上,首先在实例的字典中查找任何属性,然后是 class 的字典,然后是 superclass 的字典,依此类推继承链。