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.__subclasses__():
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(Vuln):
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(link)
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/