![](/img/trans.png)
[英]Why do I need to call 'quotes' in this scenario as opposed to using self?
[英]Why do I need to call 'self' in this case?
我是OOP的新手,我想知道為什么我需要在最后一行提供參數MainWindow。 如果我自己調用outside_func,則不需要參數,但是當我在類中調用它時,我需要提供類名稱以使其起作用。 例如,MainWindow.class_func2()引發錯誤
class MainWindow():
def __init__(self):
print("in init")
def claas_func(self):
print ("func1")
def class_func2(self):
outside_func()
def outside_func():
print('outside called')
instance = MainWindow()
MainWindow.class_func2(MainWindow)
你應該看看@staticmethod
class MainWindow():
def __init__(self):
print("in init")
def claas_func(self):
print ("func1")
@staticmethod
def class_func2():
return outside_func()
def outside_func():
print('outside called')
instance = MainWindow()
>> in init
instance.class_func2()
>> outside called
這個@static方法(本身就是一個很酷的稱為“ decorator”的東西)將使方法本身完全可調用而無需傳遞“ self”。
希望能幫助到你
試試這個吧。 您已經創建了MainWindow()的實例。 現在,您可以通過它訪問其成員。
class MainWindow():
def __init__(self):
print("in init")
def claas_func(self):
print ("func1")
def class_func2(self):
outside_func()
def outside_func():
print('outside called')
instance = MainWindow()
instance.class_func2()
還要運行它,注意它會初始化MainWindow()類2x。 我不建議使用第二種方法。 這是多余的,而且不合適。 但是這樣您就可以看到它在做什么。
class MainWindow():
def __init__(self):
print("in init")
def claas_func(self):
print ("func1")
def class_func2(self):
outside_func()
def outside_func():
print('outside called')
instance = MainWindow()
MainWindow().class_func2()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.