473,395 Members | 1,629 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,395 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 3056
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...

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.