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

Home Posts Topics Members FAQ

Something like the getattr() trick.

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

def get_link(self):
pass

class VulnInfo(Vuln):
pass

class VulnDiscuss(Vul n):
pass

def main(url):
vuln_class = ['Info', 'Discuss']
vuln = Vuln(url)
vuln._parse()
for link in vuln.get_link() :
i = VulnInfo(link)
i._parse()
d = VulnDiscuss(lin k)
d._parse()
Is there a way to get references to VulnInfo and VulnDiscuss objects using
something like the getattr trick? For example, something like:

for _class in vuln_class:
class_obj = getattr('Vuln%s ' % (_class,) ..)
a = class_obj(link)
a._parse()

getattr() takes an object as its first argument. I can't seem to figure
out how to make it work here.

--
Ayaz Ahmed Khan

A witty saying proves nothing, but saying something pointless gets
people's attention.
Feb 10 '07 #1
3 1376
On Feb 10, 3:34 pm, Ayaz Ahmed Khan <a...@dev.slash .nullwrote:
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

def get_link(self):
pass

class VulnInfo(Vuln):
pass

class VulnDiscuss(Vul n):
pass

def main(url):
vuln_class = ['Info', 'Discuss']
vuln = Vuln(url)
vuln._parse()
for link in vuln.get_link() :
i = VulnInfo(link)
i._parse()
d = VulnDiscuss(lin k)
d._parse()

Is there a way to get references to VulnInfo and VulnDiscuss objects using
something like the getattr trick? For example, something like:

for _class in vuln_class:
class_obj = getattr('Vuln%s ' % (_class,) ..)
a = class_obj(link)
a._parse()

getattr() takes an object as its first argument. I can't seem to figure
out how to make it work here.

--
Ayaz Ahmed Khan

A witty saying proves nothing, but saying something pointless gets
people's attention.
eval('Vuln' + _class)
or,
Vuln.Discuss = VulnDiscuss
getattr(Vuln, _class)

Feb 10 '07 #2
This is a really common question. What you really need here is to
lookup some value (one of the two classes) by a key (the names of the
classes). Does that sound like something familiar? You seem to need a
dictionary, where you think you want lookup some global objects by
name.

Alternatively, if you use new-style classes (by`inheriting the object
class in your base class), you could perhaps add a method such as
getSubClass() like:

class Vuln(object):
...
@classmethod
def getSubClass(cls , name):
for c in cls.__subclasse s__():
if c.__name__ == name:
return c
raise ValueError("No subclass named '%s' found." % name)

Of course, this only makes sense if you needs dont extend outside the
pattern of looking up subclasses by name. It has the advantage that
you can also put the subclasses in other modules and still look them
up from one place.

On 2/10/07, Ayaz Ahmed Khan <ay**@dev.slash .nullwrote:
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

def get_link(self):
pass

class VulnInfo(Vuln):
pass

class VulnDiscuss(Vul n):
pass

def main(url):
vuln_class = ['Info', 'Discuss']
vuln = Vuln(url)
vuln._parse()
for link in vuln.get_link() :
i = VulnInfo(link)
i._parse()
d = VulnDiscuss(lin k)
d._parse()
Is there a way to get references to VulnInfo and VulnDiscuss objects using
something like the getattr trick? For example, something like:

for _class in vuln_class:
class_obj = getattr('Vuln%s ' % (_class,) ..)
a = class_obj(link)
a._parse()

getattr() takes an object as its first argument. I can't seem to figure
out how to make it work here.

--
Ayaz Ahmed Khan

A witty saying proves nothing, but saying something pointless gets
people's attention.
--
http://mail.python.org/mailman/listinfo/python-list

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
Feb 10 '07 #3
On 2/10/07, Ayaz Ahmed Khan <ay**@dev.slash .nullwrote:
>class Vuln:

class VulnInfo(Vuln):

class VulnDiscuss(Vul n):

def main(url):
vuln_class = ['Info', 'Discuss']
vuln = Vuln(url)
vuln._parse()
for link in vuln.get_link() :
i = VulnInfo(link)
i._parse()
d = VulnDiscuss(lin k)
d._parse()
Is there a way to get references to VulnInfo and VulnDiscuss objects
In addition to what other people has suggested:

- Use some kind of registry:
register("Vuln" , Vuln, VulnInfo, VulnDiscuss)
(a dictionary would do) and then look up by name

- If all three classes are contained inside the same module, look up them
by name into globals: InfoClass = globals()["%sInfo" %
self.__class__. __name__]
(assuming self is an instance of Vuln, this would give you the VulnInfo
class)

- Replace your line: vuln_class = ['Info', 'Discuss']
with vuln_class = [VulnInfo, VulnDiscuss]

As you see, there are many ways to do that - choose what better fits your
needs.

--
Gabriel Genellina

Feb 11 '07 #4

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

Similar topics

0
1852
by: daishi | last post by:
Hi, The following code appears to be doing what I'd expect, but I'm wondering if someone could confirm that there aren't any "gotchas" hidden in using methods accessed in this way. In particular, should I be concerned that in the example below, f is different from g and h when applying f to instances of test.Sub? For my simple example things appear reasonable, but ... Thanks,
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
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
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
1
20430
by: Sergio Correia | last post by:
This works: # Module spam.py import eggs print getattr(eggs, 'omelet')(100) That is, I just call the function omelet inside the module eggs and evaulate it with the argument 100.
2
1323
by: Sledge | last post by:
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
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...
8
7991
by: Gregor Horvath | last post by:
Hi, class A(object): test = "test" class B(object): a = A() In : B.a.test
9
3993
by: Gabriel Rossetti | last post by:
Hello, I can't get getattr() to return nested functions, I tried this : .... def titi(): .... pass .... f = getattr(toto, "titi") .... print str(f) .... Traceback (most recent call last):
0
10542
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
10309
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
10289
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
9119
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
7600
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
5625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4274
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
2
3795
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2968
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.