How do you know when you look at the list of attributes and methods listed in the directory which are attributes and which are methods?

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.

+4
source share
6 answers

Instead of: " print hasattr(d1,each) ", try: " print each, type(getattr(d1,each)) ". You should find the results informative.

Also, instead of dir() try help() , which I think you're really looking for.

+7
source

Consider using the standard inspect library module - this is often the most convenient approach to introspection, packing substantial pieces of functionality (you can implement this from scratch, but reusing well-tested, well-designed code is a good thing). See http://docs.python.org/library/inspect.html for full details, but for example inspect.getmembers(foo, inspect.ismethod) is a great way to get all the foo methods (you get (name, value) pairs sorted by name).

+4
source

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.

Why is this misleading? If obj.ban() is a method, then obj.ban is the corresponding attribute. You might have this code:

 print obj.getValue() 

or

 get = obj.getValue print get() 

If you want to get a list of methods for an object, you can try this function. It is not ideal, as it will also run for called attributes that are not methods, but should be good enough for 99% of cases:

 def methods(obj): attrs = (getattr(obj, n) for n in dir(obj)) return [a for a in attrs if a.hasattr("__call__")] 
+2
source

This info module, inspired by Dive in Python, serves the purpose.

 def info(obj, spacing=20, collapse=1, variables=False): '''Print methods and their doc Strings Takes any object''' if variables: methodList = [method for method in dir(obj)] else: methodList = [method for method in dir(obj) if callable(getattr(obj,method))] #print methodList print '\n'.join(['%s %s' % (method.ljust(spacing), " ".join(str(getattr(obj,method).__doc__).split())) for method in methodList]) if __name__=='__main__': info(list) 
+2
source

Ideally, when using a complex library such as BeautifulSoup, you should consult your documentation to find out which methods each class provides. However, in the rare case when you do not have documentation available, you can check for methods using the following.

All methods that are objects themselves implement the __call__ method and can be checked using the callable () method, which returns True if the checked value has the __call__ method.

The following code should work.

 x = Die() x.roll() for attribute in dir(x) : print attribute, callable(getattr(x, attribute)) 

The above code will return true for all methods and false for all non-callable attributes (such as data members such as barring). However, this method also returns True for any called objects (for example, inner classes). you can also check if instancemethod attribute type

+1
source

There is a built-in method called called. You can apply it to any object, and it will return True / False depending on whether it can be called. eg.

 >>> def foo(): ... print "This is the only function now" ... >>> localDictionary = dir() >>> for item in localDictionary: ... print repr(item) + "is callable: " + str(callable(locals()[item])) '__builtins__'is callable: False '__doc__'is callable: False '__name__'is callable: False 'foo'is callable: True 

Note that calling locals () returns a dictionary containing everything that is defined in your current scope. I did this because the elements from the dictionary are just strings, and we need to actually run the called object.

+1
source

All Articles