annoying behavior

Larry Bates lbates at syscononline.com
Tue Sep 28 16:26:26 EDT 2004


Elbert Lev wrote:
> # here is the problem I ran into:
> 
> class foo:
>     def __init__(self, host):
>         self.f()
>         self.r = True
>     
>     def f(self):
>         if self.r:
>             #<do something>
>             pass
>         else:
>             #<do something else>
>             pass
> 
> f = foo("1234")
> 
> #here is the output:
> 
> #Traceback (most recent call last):
> #  File "G:\MyProjects\Python\Little\inconv.py", line 16, in ?
> #    f = foo("1234")
> #  File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__
> #    self.f()
> #  File "G:\MyProjects\Python\Little\inconv.py", line 9, in f
> #    if self.r:
> #AttributeError: foo instance has no attribute 'r'
> 
> # I understand why does this happen, but, to tell the truth,
> # this feature is very annoying. 
> # Are there any plans to relax this restriction? 
> # In 3.0 :)?

Just put the lines in the correct order:

  class foo:
      def __init__(self, host):
          self.r = True
          self.f()

      def f(self):
          if self.r:
              #<do something>
              pass
          else:
              #<do something else>
              pass

  f = foo("1234")

You can't ask if self.r is True (which is what you do
in the second line of the f() method) before it actually
exists.

Larry Bates
Syscon, Inc.



More information about the Python-list mailing list