简体   繁体   English

Python 3 OOP 将方法重定向到属性的方法

[英]Python 3 OOP Redirect method to the attribute's method

Let suppose I have a class called A with an attribute b (class or object attribute, it doesn't matter) from a class B .假设我有一个名为A的 class ,其属性b (类或 object 属性,没关系)来自 class B

There is a B method called method_B有一个B方法叫做method_B

If I create an object a from class A , and I call a.method_b() from a , I want to be redirected to abmethod_b()如果我从 class A创建一个 object a ,然后从a调用 a.method_b a.method_b() ,我想被重定向到abmethod_b()

The corresponding code:对应代码:

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()

In fact, I want to avoid rewritting the method_B in class A like this:事实上,我想避免像这样method_B A中的 method_B :

class A():

  ...

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

I have looked up an use of property and with descriptor but I don't know how to adapt them (if I can adapt them of course)我已经查找了属性描述符的使用,但我不知道如何调整它们(如果我当然可以调整它们)

Thank you in advance for your help预先感谢您的帮助

Actually, when you are trying to get method_B() by creating object of class A, this will cause error since method_B() is not present in the class A. Your question is that you don't want to rewrite method_B() in class A, so you can use inheritance then you can get the same result from these below mentioned line of code. Actually, when you are trying to get method_B() by creating object of class A, this will cause error since method_B() is not present in the class A. Your question is that you don't want to rewrite method_B() in class A,所以你可以使用 inheritance 然后你可以从下面提到的这些代码行中得到相同的结果。

this: 这个:

a.method_B()

will be same as if you will follow below code by using inheritance: 就像您使用 inheritance 遵循以下代码一样:

abmethod_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: abmethod_B()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM