子类中的赋值和覆盖之间有什么区别?

问题描述 投票:0回答:1

这不是作业问题。实际上,这只是困扰我了一段时间,似乎对Google来说特别难]

在下面的代码中,任何人都可以解释FirstChildSecondChild之间的实际差异。从实验中可以明显看出,“ work”和可以说SecondChild的效率都稍高。但是这两个行为方式我缺少什么吗?它们不同吗?如何不同吗?

import collections


class Parent:

    def send_message(self, message: str):
        pass


class FirstChild(Parent):

    def __init__(self):
        self.message_queue = collections.deque()

    def send_message(self, message: str):
        self.message_queue.append(message)


class SecondChild(Parent):

    def __init__(self):
        self.message_queue = collections.deque()
        self.send_message = self.message_queue.append
python
1个回答
0
投票
FirstChild

class中创建一个称为send_message的描述符。当您执行instance.send_message时,解释器首先在实例__dict__中搜索名称,然后是类。在类中找到该函数后,该函数将与实例绑定[以创建不接受self的方法对象。每次您执行查找时都会发生,看起来像

method = type(instance).send_message.__get__(type(instance), instance) SecondChild”将绑定方法分配为
instance
中的属性send_message。它剪切出自己的类对象中的查找以及deque类对象中的查找和绑定。这可能就是为什么它看起来效率更高的原因。

这些方法之间的主要实际差异是send_message中的SecondChild不可替代。由于函数是非数据描述符(它们具有__get__方法但不具有__set__(是的,函数具有类类型和方法,就像其他任何对象一样)),因此``SecondChild send_message中的实例属性will always trump any class-level function. This means that a child of ] SecondChildthat calls the parentinit它创建的method will hide any implementation of send_message`。

您可能会发现官方描述符指南非常有用:https://docs.python.org/3/howto/descriptor.html

© www.soinside.com 2019 - 2024. All rights reserved.