简体   繁体   中英

python how to find which parent classes define methods of a child object

For context, I will use the example that prompted this question which is the DNA sequence class of Scikit-Bio.

The base class is a generic python sequence class. A Sequence class inherits from that class for sequences that are specifically nucleic acids (DNA, RNA ...). Finally, there is a DNA class that inherits from Sequence that enforces the specific alphabet of DNA.

So the following codes lists all the attributes of a DNA object.

from skbio import DNA

d = DNA('ACTGACTG')
for attr in dir(d):
    # All the attributes of d.

How can I find which parent class each attribute belongs to? The reason why I am interested in this is that I am looking through the source code, and I want to be able to know which file I can find each method that I want to look at.

The best I can think of is something like this:

for attr in dir(d)
    print type(attr)

But this just returns all string types (I guess dir() returns a list of strings).

How can I achieve this in python? Is there an inherent reason to not attemps this at all? Or is this something that comes up often in OOP?

Attributes don't typically belong to any class. Attributes typically belong to the object of which they are an attribute.

Methods, however, relate intimately to the class in which they are defined.

Consider this program:

class base(object):
    def create_attrib_a(self):
        self.a = 1
class derived(base):
    def create_attrib_b(self):
        self.b = 1
def create_attrib_c(obj):
   obj.c = 1

import inspect

o = derived()
o.create_attrib_a()
o.create_attrib_b()
create_attrib_c(o)
o.d = 1

# The objects attributes are relatively anonymous
print o.__dict__

# But the class's methods have lots of information available
for name, value in inspect.getmembers(o, inspect.ismethod):
    print 'Method=%s, filename=%s, line number=%d'%(
        name,
        value.im_func.func_code.co_filename,
        value.im_func.func_code.co_firstlineno)

As you can see, each of the attributes a , b , c and d are associated with the object bound to o . None of them relate, in any technical sense, to any specific class.

However, the methods create_attrib_a and create_attrib_b carry precisely the information you desire. See how the inspect module can retrieve the filename and line number of their definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM