简体   繁体   中英

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. 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. For example, MainWindow.class_func2() throws an error

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

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'.

Hope it helps

Try this instead. You have created an instance of 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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM