简体   繁体   English

调用同级方法python3吗?

[英]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. 为了节省代码,我想在python 3的同一类中调用另一个方法。不幸的是,我只能使用一种具有固定名称的对象的解决方案。 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. 调用self.secondMethod()是正确的方法。

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

Here is the proof: Ideone online compiler 这是证明: Ideone在线编译器

Please don't publish code with German comments in it next time. 请下次不要发布带有德语注释的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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