473,803 Members | 3,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getattr() question

Hi.

I am trying to dynamically load a class and attributes at run time. I
do not know what classes will be referenced until run time. I have it
loading the module correctly, but when I use getattr to access the
class and its attributes everything works except that I get additional
unwanted output. The code

testclass.py:

#!/usr/bin/python

class testclass(objec t):

myname = ""

def __init__(self, name):
self.myname = name

def view(self):
print "hello %s" % self.myname

test.py:

#!/usr/bin/python

import sys
sys.path.append ('.')
from pprint import pprint

if __name__ == '__main__':
myname = "testclass"
myaction = "view"
try:
tc = __import__(myna me)
myclass = getattr(tc,myna me)
myinstance = getattr(myclass ('python n00b'), myaction,
myaction)
pprint(myinstan ce())
except ImportError:
"error"

Here is the output that I get:

user@debian:~/$ python test.py
hello python n00b
None
user@debian:~/$
Why is it printing 'None'? What am I doing wrong. I appreciate any
help.
Dec 22 '07 #1
2 1323
On Dec 23, 10:39 am, Sledge <andrew.j.sle.. .@gmail.comwrot e:
Hi.

I am trying to dynamically load a class and attributes at run time. I
do not know what classes will be referenced until run time. I have it
loading the module correctly, but when I use getattr to access the
class and its attributes everything works except that I get additional
unwanted output. The code

testclass.py:

#!/usr/bin/python

class testclass(objec t):

myname = ""

def __init__(self, name):
self.myname = name

def view(self):
print "hello %s" % self.myname

test.py:

#!/usr/bin/python

import sys
sys.path.append ('.')
from pprint import pprint

if __name__ == '__main__':
myname = "testclass"
myaction = "view"
try:
tc = __import__(myna me)
myclass = getattr(tc,myna me)
myinstance = getattr(myclass ('python n00b'), myaction,
myaction)
pprint(myinstan ce())
except ImportError:
"error"
What do you expect to see if the import fails?
>
Here is the output that I get:

user@debian:~/$ python test.py
hello python n00b
None
user@debian:~/$

Why is it printing 'None'? What am I doing wrong. I appreciate any
help.
The problem is nothing to do with using getattr; it "works" in the
sense that it does what you appear to want it to.

You have *two* explict outputting statements: the print statement in
the first file and the pprint invocation in the second file. Seems
fairly obvious that it's not the first of these. So dissect
"pprint(myinsta nce())".

myinstance is bound to the view method [in the first file] which
(implicitly) returns None. So you are in effect doing pprint(None).

Aside: give your fingers a rest: don't type "my" so often.

Dec 23 '07 #2
On Dec 22, 7:14 pm, John Machin <sjmac...@lexic on.netwrote:
On Dec 23, 10:39 am, Sledge <andrew.j.sle.. .@gmail.comwrot e:
Hi.
I am trying to dynamically load a class and attributes at run time. I
do not know what classes will be referenced until run time. I have it
loading the module correctly, but when I use getattr to access the
class and its attributes everything works except that I get additional
unwanted output. The code
testclass.py:
#!/usr/bin/python
class testclass(objec t):
myname = ""
def __init__(self, name):
self.myname = name
def view(self):
print "hello %s" % self.myname
test.py:
#!/usr/bin/python
import sys
sys.path.append ('.')
from pprint import pprint
if __name__ == '__main__':
myname = "testclass"
myaction = "view"
try:
tc = __import__(myna me)
myclass = getattr(tc,myna me)
myinstance = getattr(myclass ('python n00b'), myaction,
myaction)
pprint(myinstan ce())
except ImportError:
"error"

What do you expect to see if the import fails?
Here is the output that I get:
user@debian:~/$ python test.py
hello python n00b
None
user@debian:~/$
Why is it printing 'None'? What am I doing wrong. I appreciate any
help.

The problem is nothing to do with using getattr; it "works" in the
sense that it does what you appear to want it to.

You have *two* explict outputting statements: the print statement in
the first file and the pprint invocation in the second file. Seems
fairly obvious that it's not the first of these. So dissect
"pprint(myinsta nce())".

myinstance is bound to the view method [in the first file] which
(implicitly) returns None. So you are in effect doing pprint(None).
that did the trick. How could I have missed something so obvious?
>
Aside: give your fingers a rest: don't type "my" so often.
It was just for demonstration purposes :). Thanks for your help John.
Dec 23 '07 #3

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

Similar topics

3
2075
by: Johnny | last post by:
Hi, I wonder what is the difference between the built-in function getattr() and the normal call of a function of a class. Here is the details: getattr( object, name) Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object's attributes,
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
13
4188
by: Pierre | last post by:
Hi, Sorry in advance, english is not my main language :/ I'd like to customize the result obtained by getattr on an object : if the object has the requested property then return it BUT if the object doesn't has actually this property return something else. In my case, I can't use getattr(object, property, default_value).
4
2428
by: Hole | last post by:
Hi There! I'm trying to use Zope and the product OpenFlow. I got the following error while I was using the built-in function getattr() to retrieve an OpenFlow object: attribute name must be string
4
3687
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
2
5563
by: indiarocks | last post by:
Just a basic question .... When using getattr for a specific method from a different class, can we somehow tell getattr to do a case-insensitive search. Say for eg. m = getattr(obj.__class__,'SetupClass') where obj is a object of a specific class. If SetupClass is declared as setUPClass or in any other way, the return value of m is going to be None, so can this be avoided in any way Thanks
3
1377
by: Ayaz Ahmed Khan | last post by:
I'm working with the following class heirarchy (I've snipped out the code from the classes): class Vuln: def __init__(self, url): pass def _parse(self): pass
3
1560
by: Jm lists | last post by:
Hello, Since I can write the statement like: Test whether a path is a directory Why do I still need the getattr() func as below? Test whether a path is a directory
3
3080
numberwhun
by: numberwhun | last post by:
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...
0
9700
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
9564
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
10546
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
10310
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
10068
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
9121
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
7603
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
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3796
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.