从主对象访问受保护复合对象的方法

问题描述

我想验证我使用复合和受保护对象方法的方式是否正确。 此处将示例代码放在我使用 B 类对象访问 A 类方法的位置。

class A:
    # initialisation of class A
    def __init__(self):
        pass
    
    # method a,I want to call this method from other's object
    def method_a(self):
        print("Perform operation a")
        

class B:
    def __init__(self):
        # initialisation of class B
        # Creating composite and protected object
        self._a = A()
        
    # introducing a method to support a method of a protected object(self._a)
    def via_b(self):
        # calling method of class A
        self._a.method_a()
        

# creating object of class B
b = B()

#Way1: # is this valid to call?
b._a.method_a()

# Way2: or I should use this?
b.via_b()```

In way 2 I see the disadvantage that just to use a method of class A,need to introduce a method in class B.
Can I use Way 1 in code?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)