top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Class hierarchy problem in Python

0 votes
471 views

I have a hierarchy of classes (SubA, SubAB, SubB, ..., SubBCA, SubC,...), each of which is inheriting from a chain of superclasses with a common baseclass(Sup) on top. (So far, no problem)

Now, I want to create instances of the correct subclasstype as decided by the common baseclass, like this:

i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)

where i can be of any class except Sup itself (as decided by Sup)

Now, the problem:

How to design the __new__() and __init__() methods for the various classes in order to achieve what I want?

posted Aug 6, 2013 by Deepankar Dubey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Try  factory function instead of the class itself? Then all you need to do is call the appropriate class.

1 Answer

+1 vote

Keep it simple, use a function:

def make(*args):
 class_ = deduce_correct_class(*args)
 return class_(*args)

That way you won't even need any __new__() methods.

answer Aug 6, 2013 by Sumit Pokharna
Similar Questions
+3 votes

Is there way to get list of instances of particular class through class itself? via metaclass or any other method?

If class is object is it possible to delete it? If it is possible then how instances of that class will behave?

+1 vote

I want to build a class that perform various functions to the content(or lines) of any given file. I want to first include the opening and reading file function into that class, then add other methods.

Here is what I wrote for opening file and reading the lines:

class FileOpration:
 def __init__(self,name):
 self.name = name
 self.filename = self.name
 def readAllline(self):
 open(self.name).readlines()

file1 = FileOpration("myfile.txt")
print file1.filename
allines = file1.readAllline()
print allines

I define self.name variable because I want to store the specific file that I read. This works fine by the test code of print file1.filename. I saw "myfile.txt" on the terminal output.

However, the readAllline() method dose not work. The code only give me "None" as the output on terminal

+2 votes

I would like to apply the Pool.map method to a member of a class. Here is a small example that shows what I would like to do:

from multiprocessing import Pool

class A(object):
 def __init__(self,x):
 self.value = x
 def fun(self,x):
 return self.value**x

l = range(10)

p = Pool(4)

op = p.map(A.fun,l)

using this with the normal map doesn't cause any problem

This fails because it says that the methods can't be pickled. (I assume it has something to do with the note in the documentation: "functionality within this package requires that the __main__ module be importable by the children.", which is obscure to me).

I would like to understand two things: why my code fails and when I can expect it to fail? what is a possible workaround?

...