Python forward declaration of functions inside classes

I first hit Python and am stuck here:

class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

def foo(string):
    return string

At this moment I upload the above file (with a name classes), and this happens:

$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from classes import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "classes.py", line 5, in <module>
    class B(A):
  File "classes.py", line 6, in B
    b = foo("boo")
NameError: name 'foo' is not defined

Notice how the error is in class B, where it foois called directly, not from __init__. Note also that I have not created an instance of the class yet B.

First question:

  • Why is he returning an error? I do not create a class.

Moving. The "problem" is solved by moving the definition of a foo()few lines above:

def foo(string):
    return string

class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

Now i can do

>>> x = B()
>>> x.b
'boo'

but i can't do

>>> y = A()
>>> y.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'a'

Additional questions:

  • What didn’t I understand about __init__?

I do not think this is the same as the declaration , so I hope this question is not a duplicate.

, DSL, , python.

+3
3

-, B foo() . A , foo() - foo.

y.a , self.a = foo('stirng'). a = foo('stirng') a __ init __.

__ init __ self.

+6

, __init__, , (t1). , , , .

, Outlook Python, . , . , , , Python class:

  • ( ) .
  • .
  • - __dict__.
  • .

, , ; , - , ! ( , .)

:

def foo(x=bar()): pass

bar , foo .


, -:

class A():
    def __init__(self):
        self.a = foo()

a = A()

def foo():
    pass
+1
class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

a - - A , foo ( "baa" ) A.

b - - B b, foo ( "boo" ) .

In general, you can reference functions and classes that do not yet exist while they are defined before you evaluate the link (i.e. before you actually try to call the function).

+1
source

Source: https://habr.com/ru/post/1796677/