[Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?
boB Stepp
robertvstepp at gmail.com
Wed Jan 20 23:34:59 EST 2016
My intent was to deliberately introduce an error into my class definition:
>>> class Hmm(object):
def __init__(self, sigh_type, sigh_strength):
self.sigh_type = sigh_type
self.sigh_strength = sigh_strength
def snort(self):
if self.sigh_strength == 'low':
print("snort")
elif self.sigh_strength == 'med':
print("Snort!")
elif self.sigh_strenght == 'high':
print("SNORT!!!")
else:
print("Hmm...")
def sigh():
if self.sigh_type == 'quiet':
print("pssssss")
elif self.sigh_type == 'annoying':
print("Whoosh!")
elif self.sigh_type == 'loud':
print("HEAVY SIGH!!!")
else:
print("HMM!!!")
I omitted "self" from the sigh() method to see what would happen plus
some other things.
>>> humdrum = Hmm('quiet', 'low')
>>> humdrum.snort()
snort
>>> humdrum.sigh_strength = 'med'
>>> humdrum.snort()
Snort!
>>> humdrum.sigh_strenght = 'high'
>>> humdrum.snort()
Snort!
At this point I wondered why my output was not "SNORT!!!". Then I
noticed my typo. But now I wonder why I did not get an error from
this typo?
>>> humdrum.sigh_strength = 'high'
>>> humdrum.snort()
SNORT!!!
>>> humdrum.sigh()
Traceback (most recent call last):
File "<pyshell#232>", line 1, in <module>
humdrum.sigh()
TypeError: sigh() takes 0 positional arguments but 1 was given
This was my original point in doing all of this, to see what would
result if I omitted "self". I am pretty sure the error is because the
object instance gets automatically passed to the sigh() method, but by
leaving the "self" parameter out in the method definition, I have a
mismatch between what was defined (0 parameters) and what was passed
to the method (1 argument).
>>> humdrum.sigh_strenght
'high'
But what about this? It seems like I can use the humdrum arguments
outside of the Hmm class and merrily define new variables. Why is
this? Is this potentially useful behavior?
--
boB
More information about the Tutor
mailing list