user3376020
user3376020

Reputation:

call a method of class instance located inside a python list

I have following classes in python:

I have a list in ElemMatch class which is supposed to have instances of QueryElement.

My problem is in invoking a method called compute from the instances inside the list, in ElemMatch class(compute method). The type of object inside the list is not identified by Python, and I do not know how to assign a type to the list. I do not have such a problem in Java since I could 'cast' to a type I like, but here I do not know how to solve it.

I appreciate if you could help.

class QueryElement(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def addQueryElement(self, queryElement):        
        raise NotImplementedError( "Should have implemented this" )


    @abc.abstractmethod
    def compute(self):      
        raise NotImplementedError( "Should have implemented this" )


class ElemMatch(QueryElement):

    def __init__(self):
        self._queryElements = []

    def addQueryElement(self, queryElement):
        self._queryElements.append(queryElement)

    def compute(self):
        elemMatch = {}
        if len (self._queryElements) > 0:
            elemMatch['e'] = self._queryElements[0].compute()

        return elemMatch    


class GT(QueryElement):

    def __init__(self):
        print 'someThing'

    def addQueryElement(self, queryElement):
        return None

    def compute(self):
        print 'compute GT!' 

class PALLAS(object):
    def foo(self):
        gt = GT()
        elemMatch = ElemMatch()

        elemMatch.addQueryElement(gt)
        elemMatch.compute()

p = PALLAS()
p.foo()

Upvotes: 0

Views: 3314

Answers (1)

chepner
chepner

Reputation: 532428

In Python, the objects, not the names referring to them, are typed. If the object has a compute method, you can call it, regardless of what the type of the object is.

A quick example:

class A(object):
    def foo(self):
        print "I'm an A"

class B(object):
    def foo(self):
        print "I'm a B"

lst = [A(), A(), B(), A(), B()]
for l in lst:
    l.foo()

Each element of lst is either an instance of A or of B. Since both have a method named foo, you don't have to know the type of the object referenced by l each time through the loop; the lookup of foo will find the correct method.

This is commonly referred to as duck typing; if l looks like a duck and acts like a duck (i.e., if it has a method foo), then it is a duck (i.e., then we can call the method foo).

Upvotes: 1

Related Questions