473,804 Members | 3,108 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help needed in understanding the "getattr()" function

numberwhun
3,509 Recognized Expert Moderator Specialist
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 3080
Motoma
3,237 Recognized Expert Specialist
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 Recognized Expert Moderator Specialist
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 Recognized Expert Moderator Specialist
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
6426
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 subclass provides actual values for the attributes and (2) that no "client" module adds or removes attributes or properties, but I don't know how to do those.) I don't understand what I'm doing wrong, or maybe what I want to do is impossible. ...
49
2881
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 Vainio http://www.students.tut.fi/~vainio24
7
3279
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 all written data to uppercase: class UpperOut: def __init__(self, outfile): self.__outfile = outfile def write(self, s):
8
2345
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 number 2. I actually wrote a java function that did this a couple of years ago, in school, as an excersise in "binary trees". I lost it, and most of my programming knowledge, but I figured perhaps there is a way to do this easily in python? It...
2
3097
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 run time while parsing the XML file. I wonder what is the best solution for this problem? I also have some problem about the "import". How should I design my packages? Say, I have all code locates at c:\projects\sami, "c:\project" is in my...
40
3053
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 goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers"...
5
1668
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 use 'exec' - is that what would be necessary?
8
1905
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 >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
4
3688
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 with getattr. Comments would be appreciated. Thanks, -Emin
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
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
10564
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
10320
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...
0
9134
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...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.