【问题标题】:Python 3 OOP Redirect method to the attribute's methodPython 3 OOP 将方法重定向到属性的方法
【发布时间】:2020-08-03 03:10:28
【问题描述】:

假设我有一个名为A 的类,其属性b(类或对象属性,没关系)来自类B

有一个B 方法称为method_B

如果我从类A 创建一个对象a,并从a 调用a.method_b(),我想被重定向到a.b.method_b()

对应代码:

class A():

  def __init__(self):
    self.b = B()

class B():

  def __init__(self):
    self.val = 'a string'

  def method_B(self):
    # do something with self.val for example

# MAIN

a = A()

# this:
a.method_B()

# should be the same as:
a.b.method_B()

事实上,我想避免像这样重写A类中的method_B

class A():

  ...

  def method_B():
    self.b.method_B()

我已经查找了 propertydescriptor 的用法,但我不知道如何调整它们(如果我当然可以调整它们)

提前感谢您的帮助

【问题讨论】:

  • 您正在寻找 Zope 和 Acquisition。

标签: python-3.x oop methods


【解决方案1】:

实际上,当您尝试通过创建类 A 的对象来获取 method_B() 时,这将导致错误,因为类 A 中不存在 method_B()。 您的问题是您不想在 A 类中重写 method_B(),因此您可以使用继承,然后您可以从下面提到的这些代码行中获得相同的结果。

这:

a.method_B()

就像您将使用继承遵循以下代码一样:

a.b.method_B()

class B():

  def __init__(self):
    self.val = 'a string'

  def method_B(self):
      print("method B")
   

class A(B):
    def __init__(self):
        self.b = B()
# MAIN

a = A()
b = B()
# this:
a.method_B()

# should be the same as:
a.b.method_B()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2018-10-23
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多