你在說什麼是object oriented programming。我建議你在大學或online上選修一門課程。不過,我已經採取了時間掀起一個簡單的例子做什麼,我覺得你想要它做的:
class A(object):
def __init__(self):
print("hello world")
def new_print(self, some_word):
print(some_word.swapcase())
@staticmethod
def newer_print(some_word):
print(some_word.lower())
class B(object):
def __init__(self):
print("world")
#create the object of Class A and then call the method
temp = A()
temp.new_print("This is a test")
#call the static method of Class A
A.newer_print("Just one more test")
if __name__ == "__main__":
#create the object for Class B
test = B()
注意Class A
有兩個方法(除了__init__
)。第一個(new_print
)要求在調用方法之前實例化該類的一個對象。第二個(newer_print
)可以靜態運行。
調用另一個類的方法是簡單地完成或者:
- 創建類的一個對象,並調用它的方法,或者
- 調用類的靜態方法
如果你看看在B的實例化方法中,你會看到這兩種情況都被證明了。
粘貼我們你的代碼(格式爲Ctrl-K),找出具體的問題,然後我們可以批評它。 – smci 2014-10-17 22:12:03
*「我試圖創建一個使用另一個對象的函數的類」*你的意思是B類使用A的方法,但B不是A的子類? B中的方法可以調用A實例的方法,但只有一個深度的調用級別......不違反Demeter法則*(「對象引用中最多一個點」)* – smci 2014-10-17 22:14:51
...或否則,如果你想讓A和B兩個類共享一些方法,那麼讓它們都從一個公共基類C繼承。你可以強制該方法是抽象的/沒有一個默認的實現,通過'raise Exception'。沒有看到具體細節和代碼,很難知道你真正想要什麼。 – smci 2014-10-17 22:16:39