annoying behavior
Peter Otten
__peter__ at web.de
Tue Sep 28 13:16:31 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,
...you don't seem to. An attribute is not there until you set it.
> # this feature is very annoying.
> # Are there any plans to relax this restriction?
> # In 3.0 :)?
No chance. Even as a non-developer I dare say that.
Either modify __init__():
def __init__(self):
self.r = False # for example
self.f()
self.r = True
or change f():
def f(self):
if hasattr(self, "r"):
# do something
else:
# do something else
Peter
More information about the Python-list
mailing list