python - 蟒蛇 | 使用子类对象从父类访问变量是否比从子类访问相同变量慢?
问题描述
class Animal():
def add(self):
self.weight = 10
self.color = 'Black'
class Bird(Animal):
def add(self):
self.feather_type = 'Long'
super().add()
b = Bird()
b.add()
print(b.weight)
print(b.color)
print(b.feather_type) // will this be faster than above 2 statements ?
从父类、子类的对象访问变量是否比直接从子类访问变量慢?
如果父类中有很多变量 10+(包括数组和数据模型对象),并且每个变量都在子类中使用,是否建议在每个子类中添加这些变量并从父类中删除以获得更好的性能?(当我写这篇文章时听起来很愚蠢,因为这与整个继承概念相矛盾)
将它们作为局部变量存储在子类函数中,然后访问它们会更好吗?(如果多次使用)
与代码中一样,变量未在__init__
方法中初始化。在这种情况下,这会使程序变慢吗?这样做是因为,并非所有操作都需要类的所有属性。因此,何时并根据需要对它们进行初始化和使用。(注意:注意在执行操作之前创建所需的属性)。
如果父类中有很多变量 10+(包括数组和数据模型对象),并且每个变量都在子类中使用,是否建议在每个子类中添加这些变量并从父类中删除以获得更好的性能?(当我写这篇文章时听起来很愚蠢,因为这与整个继承概念相矛盾)
解决方案
让我们对其进行基准测试并找出答案。为了测试这样的事情,我喜欢使用我编写的模块:timerit。
import timerit
class Animal():
def add(self):
self.weight = 10
self.color = 'Black'
class Bird(Animal):
def add(self):
self.feather_type = 'Long'
super().add()
b = Bird()
b.add()
ti = timerit.Timerit(1000000, bestof=100, verbose=2)
for timer in ti.reset('Access weight'):
with timer:
b.weight
for timer in ti.reset('Access color'):
with timer:
b.color
for timer in ti.reset('Access feather_type'):
with timer:
b.feather_type
这导致
Timed Access weight for: 1000000 loops, best of 100
time per loop: best=347.005 ns, mean=370.222 ± 17.2 ns
Timed Access color for: 1000000 loops, best of 100
time per loop: best=350.992 ns, mean=367.194 ± 9.5 ns
Timed Access feather_type for: 1000000 loops, best of 100
time per loop: best=348.984 ns, mean=367.680 ± 11.9 ns
因此,不,它们之间似乎没有任何显着差异。
推荐阅读
- pyinstaller - PyInstaller:尝试运行分发文件时出现 FileNotFoundError
- github - 当 access_token 过期时, github api to refresh_token 会抛出 bad_refresh_token 错误
- qt - 将 QTextStream 转换为 QByteArray
- javascript - 对象对象显示在反应中的选择标签中
- java - Spring Boot 嵌入式 Apache Derby
- kubernetes - 如何经营一次性工作?
- python - 如何在 Pandas 中找到方法的源代码?
- android - RenderScript 删除位图上带有 alpha 的像素
- c++ - 在 C++ 中寻找排列和组合
- laravel - 如何在登录时自定义 laravel 护照错误?