I am trying to learn how to program in Python and am focusing on a better understanding of how to use standard and other modules. The dir function seems really powerful in the interpreter, but I wonder if I am missing something due to my lack of OOP background. Using the S.Lotts book, I decided to use its Die class to learn more about the syntax and usage of classes and instances.
Here is the source code:
class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value
I looked at this, and after creating some instances, I wondered if the meaning of the word was a keyword in some way and what the use of the dictionary object was in the class instruction, and so I decided to find out by changing the class definition to the following:
class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban
This change showed me that I got the same behavior from my instances, but the following methods / attributes were missing from the instances when I did the dir:
'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__'
I also found out that when I did the dir on the instance, I got an additional ban keyword, which I finally figured out was an attribute of my instance. This helped me understand that I could use d1.ban to access the value of my instance. The only reason I could understand that this is an attribute, I typed d1.happy and got an AttributeError . I realized that d1.GetValue was a method related to Die, because this is what the translator told me.
Therefore, when I try to use some complex but useful module, for example BeautifulSoup, how to find out which of the listed things are attributes of my instance or methods of my instance after entering dir (instance) . I would need to know this because it shocked me that with attributes I call the result of the method and with the help of methods that call the function on my instance.
This question is probably too verbose, but it certainly helped me better understand the difference between attributes and methods. In particular, when I look at the result of calling dir on an instance of my Die class, I see this
['__doc__', '__module__', 'ban', 'getValue', 'roll']
Thus, it would be useful to find out by looking at the list which are the attributes and which are the methods, without resorting to the trial version and the error or result for input to hasattr (myInstance, suspectedAttributeName) .
After posting the question I tried
for each in dir(d1): print hasattr(d1,each)
which tells me strictly speaking that all methods are attributes. but I cannot call the method without () , so it seems to me that hasattr () is misleading.