简体   繁体   中英

Using a method in another method before definition in same class?

This code works:

def funct_a():
    funct_b()
    print("this is func a")

def funct_b():
    print("this is funct_b")

funct_a()

But this doesn't, why?

class funct():
    def funct_a(self):
        funct_b()
        print("this is func a")
    def funct_b(self):
        print("this is funct b")
x = funct()
x.funct_a()

Error:

NameError: name 'funct_b' is not defined

Why does one work but the other doesn't? If I use a undefined function in another function it works perfectly but if I use an undefined method in another method it gives me name error why?

Why first code works?

because when funct_a() is called, funct_b has already been defined

Why second code doesn't?

because by using funct_b() interpreter searches for a function defined outside the class scope, not the funct class method. use self.funct_b()

PS dont post screenshots, but paste code instead

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