Skip to main content
 首页 » 编程设计

python之在 __init__ 中创建一个函数作为 else

2025年05月04日16bonelee

如何在 __init__ 中获取 if/else 中的函数:

class Foo(object): 
    def __init__(self, q, **keywords): 
        if a == "": 
            print "No empty strings" 
        else: 
            def on_g(self, response): 
                if response.error: 
                    print "Check your internet settings" 
                else: 
                    self.Bar() 
            http_client.fetch("http://www.google.com/", self.on_g) 

因为如果我输入空字符串,程序不会读取 on_g()!

如果我在外部使用 on_g() 与 __init__() 并行,我需要一个已声明的变量,例如:

class Foo(object): 
    def __init__(self, q, **keywords): 
        if a == "": 
            print "No empty strings" 
        else: 
            self.on_g() 
   def on_g(self): 
       print 'hello there' 

将返回你好

请您参考如下方法:

你的错误在

http_client.fetch("http://www.google.com/", self.on_g) 

应该是

http_client.fetch("http://www.google.com/", on_g) 

因为你定义了一个函数,而不是一个方法。