首页 > 解决方案 > 蟒蛇 | 使用子类对象从父类访问变量是否比从子类访问相同变量慢?

问题描述

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+(包括数组和数据模型对象),并且每个变量都在子类中使用,是否建议在每个子类中添加这些变量并从父类中删除以获得更好的性能?(当我写这篇文章时听起来很愚蠢,因为这与整个继承概念相矛盾)

标签: pythonpython-3.xclassoopinheritance

解决方案


让我们对其进行基准测试并找出答案。为了测试这样的事情,我喜欢使用我编写的模块: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

因此,不,它们之间似乎没有任何显着差异。


推荐阅读