简体   繁体   中英

making a function as an else inside an __init__

How to get a function inside if/else inside an __init__ :

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)

because the program dont read the on_g() if i put an empty string!

If i use the on_g() outside in parallel with __init__() i need a declared variable, for example:

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'

will return hello there

Your bug is in

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

which should be

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

since you defined a function, not a method.

self (the instance you're creating through __init__ ) doesn't have a on_g method.

Functions for the class -es need to be defined at the class level (as shown on your second chunk of code). They are evaluated when the class is first... erm... "looked-up"? "evaluated"?

That's why your second piece of code works. How come you can call self.on_g within the __init__ when the actual definition of the on_g method seems to come later in the code? It's an odd behavior (at a first glance) for an interpreter, right? Well... That's because when you run self.on_g() , the whole Foo class has already been evaluated and on_g has been added to the class (not to the instance !: To the class )

class Foo(object):
   def __init__(self, q, **keywords):
       [ . . . ]
       else:
           self.on_g()      # I can use self.on_g() eventhough is defined... _
                            #                                                 |
                            #                                                 |
   def on_g(self):          # <------------ LATER  ---------------------------|
       print 'hello there'

Whereas if you define your method within the __init__ , the interpreter will yell at you:

class Test(object):
    def __init__(self):
        def test(self):
            print "Hello"
        self.test()

a = Test()

Throws:

Traceback (most recent call last):
  File "./test.py", line 10, in <module>
    a = Test()
  File "./test.py", line 8, in __init__
    self.test()
AttributeError: 'Test' object has no attribute 'test'

Even if you think Oh, maybe the class doesn't have the test method because it's still within the __init__, and it will have it once the initialization is completed ... Meeeck... Wrong:

class Test(object):
    def __init__(self):
        def test(self):
            print "Hello"

a = Test()
a.test()

Same AttributeError .

If you still want to add on_g to the class at runtime (very bad idea, IMHO) you can do the interpreter's job by doing this:

class Test(object):
    def __init__(self):
        def test(self):
            print "Hello"
        self.__class__.test = test
        self.test()

a = Test()
a.test()

... which correctly prints:

Hello
Hello

Now, the two most straightforward things to do I can think of are:

  1. You move the def on_g(self) to the class level (as you showed in your second code snippet)
  2. You call your http_client.fetch with on_g as a function local to the __init__ 's scope (being picky with the language: on_g now is a function , not a method , since is not bound to an object anymore).

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

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