[英]Why do I need to call 'self' in this case?
I am new to OOP and I am wondering why I need to supply the parameter MainWindow to the final line. 我是OOP的新手,我想知道为什么我需要在最后一行提供参数MainWindow。 If I call outside_func by itself, I don't need a parameter, but when I call it within a class i need to supply the class name for it to work. 如果我自己调用outside_func,则不需要参数,但是当我在类中调用它时,我需要提供类名称以使其起作用。 For example, MainWindow.class_func2() throws an error 例如,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)
You should take a look to @staticmethod
你应该看看@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
this @staticmethod (which itself it's something really cool called 'decorator') will make the method itself entirely callable without having pass 'self'. 这个@static方法(本身就是一个很酷的称为“ decorator”的东西)将使方法本身完全可调用而无需传递“ self”。
Hope it helps 希望能帮助到你
Try this instead. 试试这个吧。 You have created an instance of MainWindow(). 您已经创建了MainWindow()的实例。 Now you can access its members with that. 现在,您可以通过它访问其成员。
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()
Also run this and notice it initializes the MainWindow() class 2x. 还要运行它,注意它会初始化MainWindow()类2x。 I DO NOT recommend this second approach. 我不建议使用第二种方法。 It is redundant and not proper. 这是多余的,而且不合适。 But just so you can kind of see what it is doing. 但是这样您就可以看到它在做什么。
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.