0

我想验证我使用复合和受保护对象方法的方式是否正确。这里将示例代码放在我使用 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?
4

0 回答 0