【问题标题】:How to use a function in two different classes with different return parameters in Python?如何在 Python 中使用具有不同返回参数的两个不同类中的函数?
【发布时间】:2017-08-02 10:35:21
【问题描述】:

我有以下 sn-p:

class one(xyz):
    def __init__(self,...):
    ....
    def myfunction(self,p,q):
        ....
        self.dummy_ = 1
        self.corr_ = 3
        return self
class two(one):
....
class three(one):

在这里,我希望 myfunction()class two 中仅返回 self.corr_ 而不是 self.dummy_,但希望在 class three 中返回所有 self.dummy_self.corr_。 实现此目的的一种方法是在从基类中删除函数后在两个类中编写相同的函数。但是有没有办法在不将myfunction() 带出class one 的情况下完成这项任务。

【问题讨论】:

  • 您正在返回self,这意味着整个对象,而不仅仅是那些特定的值。您的对象是否包含 dummy_ 属性?如果它不应该包含它,那么也许你不应该继承一个一开始就有的类。
  • 除了@deceze 回答,看看抽象类
  • 我首先从xyz 继承,它没有dummy_corr_,我在函数内部定义它,然后返回整个对象。我错过了什么吗?
  • xyz 根本不重要。您继承自一个 确实 定义这些属性的类 (one)。所以twothree 也应该展示它们。
  • 所以,这就是我想问的问题,有没有办法可以修改one 中的代码,以便self.dummy_ 继承three 而不是two

标签: python python-3.x function class


【解决方案1】:
class one(xyz):
    def __init__(self,...):
    ....
    def myfunction(self,p,q):
        ....
        self.dummy_ = 1
        self.corr_ = 3
        return self

class two(one):
    def myfunction(self,p,q):
        ....
        return self.corr

class three(one):
    ....

这称为方法覆盖。您可以覆盖您继承的方法,从而为特定子类提供该方法的不同实现。

https://docs.python.org/3.6/tutorial/classes.html https://en.wikipedia.org/wiki/Method_overriding#Python

【讨论】:

  • 如果 class one 中的 self 变量中的参数超过 2 个,并且我们想返回除一个之外的所有参数,它会起作用吗?例如,如果还有一个变量self.third,我们希望class two 中的myfunction() 返回两个自变量,而class three 中的myfunction() 返回所有自变量。
猜你喜欢
  • 2019-04-15
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多