Passing to a function -- object and method names (or references)

Midas M at a.k
Fri Jan 2 11:03:07 EST 2004


Greetings everyone,

I'm including code, for cut/paste, to better explain my question. I create a Car object then I call some of its methods. No problem. Then I try to pass, to a function, the name of the Car object and the name of one of its methods. I found one way to get this to work but can someone show me a more orthodox way? Is there a way using references to the object and somehow the method?

Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
IDLE 0.8

class Car:
    def __init__(self):
        self.milespergallon=25.0
        self.gas=20
        self.travelled=0
    def drive(self, miles):
        self.travelled=self.travelled+miles
        self.gas=self.gas-(miles/self.milespergallon)


# a test

>>> carObjA=Car() ; carObjA.drive(100) ; print carObjA.gas
16.0

# Next, trying to pass object and method "references", to someFuncA

def someFuncA(objArg1,strArg2):
    print carObjB.strMethB

>>> carObjB=carObjA ; strMethB="gas" ; someFuncA(carObjB,strMethB)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in ?
    someFuncA(carObjB,strMethB)
  File "<pyshell#15>", line 2, in someFuncA
    print carObjB.strMethB
AttributeError: Car instance has no attribute 'strMethB'

# Next, trying to pass object and method "references", to someFuncB

def someFuncB(strArg1,strArg2):
    e = "print " + strArg1 + "." + strArg2
    exec e

>>> strObjB="carObjA" ; strMethB="gas" ; someFuncB(strObjB,strMethB)
16.0

# That worked but is there a more orthodox way to pass these "references"?



More information about the Python-list mailing list