473,657 Members | 2,395 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.milesperga llon=25.0
self.gas=20
self.travelled= 0
def drive(self, miles):
self.travelled= self.travelled+ miles
self.gas=self.g as-(miles/self.milesperga llon)
# a test
carObjA=Car() ; carObjA.drive(1 00) ; print carObjA.gas 16.0

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

def someFuncA(objAr g1,strArg2):
print carObjB.strMeth B
carObjB=carObjA ; strMethB="gas" ; someFuncA(carOb jB,strMethB) Traceback (most recent call last):
File "<pyshell#1 6>", line 1, in ?
someFuncA(carOb jB,strMethB)
File "<pyshell#1 5>", line 2, in someFuncA
print carObjB.strMeth B
AttributeError: Car instance has no attribute 'strMethB'

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

def someFuncB(strAr g1,strArg2):
e = "print " + strArg1 + "." + strArg2
exec e
strObjB="carObj A" ; strMethB="gas" ; someFuncB(strOb jB,strMethB)

16.0

# That worked but is there a more orthodox way to pass these "references "?
Jul 18 '05 #1
2 1608
Midas wrote:
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?


You can access attributes with the getattr() builtin.

carGas = getattr(car, "gas")

You can refer to a method either directly

fun = car.drive
fun(123)

or via getattr():

fun = getattr(car, "drive")
fun(321)

I've modified your example to demonstrate this.

class NoGas(Exception ): pass

class Car:
def __init__(self):
self.milesperga llon = 25.0
self.gas = 20
self.travelled = 0
def drive(self, miles):
newGas = self.gas - miles/self.milesperga llon
if newGas < 0:
self.travelled += self.milesperga llon*self.gas
self.gas = 0
raise NoGas("%s miles travelled. No more gas" %
self.travelled)
self.travelled += miles
self.gas = newGas
def printAttr(obj, attrname):
"Demo for accessing an attribute by its name"
print attrname, "=", getattr(obj, attrname)

def callMethod(obj, methodname, *args):
""" Demo for calling a method determined by its name.
An arbitrary number of arguments is just passed
through to the method.
"""
method = getattr(obj, methodname)
print "calling", methodname
method(*args)

def callMethod2(met hod, *args):
""" Demo for calling a method reference.
The method is is generated by obj.method in the
calling code. Of course you can pass function
references as well
"""
method(*args)

def someFunction():
print "Welcome to the Python Motorshow"

callMethod2(som eFunction)
car = Car()
printAttr(car, "gas")
callMethod(car, "drive", 10)
printAttr(car, "gas")
while True:
printAttr(car, "travelled" )
callMethod2(car .drive, 100)

Note that my car will not travel as far as yours as it is less satisfied
with negative amounts of gas :-)

Peter
Jul 18 '05 #2
Peter Otten wrote:
You can access attributes with the getattr() builtin.

carGas = getattr(car, "gas")

You can refer to a method either directly

fun = car.drive
fun(123)

or via getattr():

fun = getattr(car, "drive")
fun(321)

I've modified your example to demonstrate this.


Thank you very much, Peter! It works nicely!

Midas
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5302
by: Ryan Malone | last post by:
Passing Dictionary object byref Ive created an ASP class that uses a dictionary object which is filled from a recordset. It passes the object to the propterty of another ASP class byref: Public Property Let dicReplaceVars(byref vdicReplaceVars) set p_ReplaceVars = vdicReplaceVars End Property
6
22514
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
8
2114
by: Dennis Myrén | last post by:
I have these tiny classes, implementing an interface through which their method Render ( CosWriter writer ) ; is called. Given a specific context, there are potentially a lot of such objects, each requiring a call to that method to fulfill their purpose. There could be 200, there could be more than 1000. That is a lot of references passed around. It feels heavy. Let us say i changed the signature of the interface method to:
3
2167
by: yysiow | last post by:
hi All in vb function can pass object, like Function test(ByVal txt As TextBox) txt.Text = "text" End Function
6
3248
by: Scott Zabolotzky | last post by:
I'm trying to pass a custom object back and forth between forms. This custom object is pulled into the app using an external reference to an assembly DLL that was given to me by a co-worker. A query-string flag is used to indicate to the page whether it should instantiate a new instance of the object or access an existing instance from the calling page. On the both pages I have a property of the page which is an instance of this custom...
3
2337
by: Caroline | last post by:
I have a CF app and I haven't found a decent obfuscator for it. I want to write a simple obfuscator, that replaces variables and methods names. Is there any way to rename all method names returned by Assembly.GetMethods, for instance, method names, my own methods and other methods such as GetType, GetHashCode, Equals, ToString - in order to scramble the code? Any ideas on how to do this? Thanks!
5
5006
by: sfeher | last post by:
Hi All, I need to call a function(loaded with appendChild) for which I have the name as a string. .... var fnName = 'fn1'; var call = fnName + '('+ param +' )'; eval(call);
9
3784
by: Greger | last post by:
Hi, I am building an architecture that passes my custom objects to and from webservices. (Our internal architecture requires me to use webservices to any suggestion to use other remoting techniques are not feasible) The question is; Given that I have a Person object with a private set for id. What is the recommended approac in passing that object to the web service
3
1615
by: John Machin | last post by:
I have stumbled across some class definitions which include all/most method names in a __slots__ "declaration". A cut-down and disguised example appears at the end of this posting. Never mind the __private_variables and the getter/setter approach, look at the list of methods in the __slots__. I note that all methods in an instance of a slotted class are read-only irrespective of whether their names are included in __slots__ or not:...
4
2113
by: alex | last post by:
I am so confused with these three concept,who can explained it?thanks so much? e.g. var f= new Function("x", "y", "return x * y"); function f(x,y){ return x*y } var f=function(x,y){
0
8306
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6164
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4152
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.