473,320 Members | 1,691 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Help needed in understanding the "getattr()" function

numberwhun
3,509 Expert Mod 2GB
Hello everyone! I am presently going through the "Dive Into Python" tutorial which I obtained from their website. No, this is not for any class, I am self-learning the Python language.

I am in Chapter 4 and reading about "Getting Object References with getattr". First, it say in there that, "you can get a reference to a function without knowing its name until run−time, by using the getattr function". That is the first thing that is a little confusing as it doesn't really elaborate on that too much, that I can tell. What does that mean? I know that you can do:

Expand|Select|Wrap|Line Numbers
  1. getattr({}, "clear)
  2.  
and that will tell you that it is the clear function of a dictionary. But, what does that have to do with not knowing the function name till runtime?

Next, if you look at example 4.10, there is a line of code in there as follows:

Expand|Select|Wrap|Line Numbers
  1. getattr(li, "append")("Moe")
  2.  
and in the text below the examples section it says:

Expand|Select|Wrap|Line Numbers
  1. In case it hasn't sunk in just how incredibly useful this is, try this: the return value of getattr is the method, which you can then call just as if you had said li.append("Moe") directly. But you didn't call the function directly; you specified the function name as a string instead.
  2.  
To tell you the truth, it hasn't really sunk in, even yet. First, it says the return value is the method (append) and that you can then call it as if you had done an:

Expand|Select|Wrap|Line Numbers
  1. li.append("Moe")
  2.  
Why not just do the direct call? Why go through all the trouble of the getattr() function?

I guess what I am getting at is, what is the getattr() function really useful for, because right now, I just don't see it? Can someone please explain it in a way that will allow me to see its full usefulness?

Sorry for the ignorance if this tends to be a clouded view!

Regards and Happy New Year!

Jeff
Dec 31 '07 #1
3 3052
Motoma
3,237 Expert 2GB
Hello everyone! I am presently going through the "Dive Into Python" tutorial which I obtained from their website. No, this is not for any class, I am self-learning the Python language.

I am in Chapter 4 and reading about "Getting Object References with getattr". First, it say in there that, "you can get a reference to a function without knowing its name until run−time, by using the getattr function". That is the first thing that is a little confusing as it doesn't really elaborate on that too much, that I can tell. What does that mean? I know that you can do:

Expand|Select|Wrap|Line Numbers
  1. getattr({}, "clear)
  2.  
and that will tell you that it is the clear function of a dictionary. But, what does that have to do with not knowing the function name till runtime?

Next, if you look at example 4.10, there is a line of code in there as follows:

Expand|Select|Wrap|Line Numbers
  1. getattr(li, "append")("Moe")
  2.  
and in the text below the examples section it says:

Expand|Select|Wrap|Line Numbers
  1. In case it hasn't sunk in just how incredibly useful this is, try this: the return value of getattr is the method, which you can then call just as if you had said li.append("Moe") directly. But you didn't call the function directly; you specified the function name as a string instead.
  2.  
To tell you the truth, it hasn't really sunk in, even yet. First, it says the return value is the method (append) and that you can then call it as if you had done an:

Expand|Select|Wrap|Line Numbers
  1. li.append("Moe")
  2.  
Why not just do the direct call? Why go through all the trouble of the getattr() function?

I guess what I am getting at is, what is the getattr() function really useful for, because right now, I just don't see it? Can someone please explain it in a way that will allow me to see its full usefulness?

Sorry for the ignorance if this tends to be a clouded view!

Regards and Happy New Year!

Jeff
The cases in the book use strings that were statically typed in. However, those strings could just as easily be taken from user input.
Dec 31 '07 #2
bvdet
2,851 Expert Mod 2GB
I have used getattr() a few times. It is useful when you need to get an attribute or method of an object with a string variable or argument. In this example, we pass an 'x', 'y' or 'z' to a function that sorts a list of point objects on the appropriate attribute.
Expand|Select|Wrap|Line Numbers
  1. def sortPts(ptlist, key='x', reverse=False):
  2.     '''
  3.     Sort a point list on the 'x', 'y' or 'z' attribute
  4.     '''
  5.     try:
  6.         def cmpItems(a,b):
  7.             if reverse:
  8.                 return -(cmp(getattr(a, key.lower()), getattr(b, key.lower())))
  9.             return cmp(getattr(a, key.lower()), getattr(b, key.lower()))
  10.         ptlist.sort(cmpItems)
  11.     except AttributeError, e:
  12.         raise AttributeError, 'Error in sortPoints() - %s' % (e)
Jan 1 '08 #3
numberwhun
3,509 Expert Mod 2GB
Ok, I somewhat see it, but the fog is still clouding my understanding. I am going to continue reading and hopefully it will lift with further examples. Thank you to both of you for your help!

Regards and Happy New Year!

Jeff
Jan 1 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Jules Dubois | last post by:
I'm want to create a superclass with nothing but attributes and properties. Some of the subclasses will do nothing but provide values for the attributes. (I'd also like to make sure (1) that the...
49
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville...
7
by: Rene Pijlman | last post by:
Section 6.5 "What is delegation?" of the FAQ says: "Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts...
8
by: Arvid Andersson | last post by:
Hello, I need to convert a string to a number, but the string can contain +,-,* and / as well as parenthesis. For example, if I have the string "30/(6+9)" I would like a function that returned the...
2
by: Tian | last post by:
I am writing a python program which needs to support some plug-ins. I have an XML file storing some dynamic structures. XML file records some class names whose instance needs to be created in the...
40
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the...
5
by: Daishi Harada | last post by:
Hi, I'd like to get the 'get2' function below to perform like the 'get1' function (I've included timeit.py results). I'm not sure how to write 'mkget' to do achieve this, however, except to...
8
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>>...
4
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.