简体   繁体   中英

Call sibling method python3?

To save on code I want to call another method within the same class in python 3. Unfortunately I can only get one solution working that uses a object with fixed name. My test code should be self explaining:

import os, sys

class Window():
    konst = "2 ENTERED SECONDMETHOD"

    def firstMethod(self):
        print("1 ENTERED FIRSTMETHOD")

    #Works
        #But this is not universal
        windowobj.secondMethod()

    #Possible solutions that did not work

        #secondMethod()
        #NameError: name 'secondMethod' is not defined

        #__class__.secondMethod()
        #TypeError: secondMethod() missing 1 required positional argument:
        #'self'

        #self.secondMethod()
        #NameError: name 'self' is not defined

        #self.__class__.secondMethod()
        #TypeError: secondMethod() missing 1 required positional argument:
        #'self'

        #super().secondMethod()
        #AttributeError: 'super' object has no attribute 'secondMethod'

    def secondMethod(self):
        print(self.konst)

#Create Object
windowobj = Window()

windowobj.firstMethod()

Calling self.secondMethod() is the correct way.

def firstMethod(self):
    print("1 ENTERED FIRSTMETHOD")
    self.secondMethod()

Here is the proof: Ideone online compiler

Please don't publish code with German comments in it next time.

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