I am writing a project with two classes:

1 factory class and 1 "fragment" class.

The factory class creates fragments from a given input file. For example, if there was a file that was 100 bytes in size, the factory class would create 10 fragments of 10 bytes each.

The problem I am having is to dynamically create fragments from a class method. I need to create fragments such as:

f1, f2, f3 depending on the number of fragments created (which is not known at runtime).

This is being created as a module so once the factory class creates the fragment, I should be able to do certain things to certain fragments such as:

f1.get_data() which would get the character representation of the specific fragment.

How do I dynamically create fragments with names f1,f2,f3, etc based on the amount of fragments?

What version of Python do you have?

Use a dictionary to store the class instances.

class ClassTest :
   def __init__ (self, desc2="***") :
      self.field1 = "*"
      self.field2 = 0
      self.field3 = desc2

   def chg_field1(self, value):
      self.field1 = value


#==========================================================================
class_dict = {}
class_dict[1]=ClassTest("First Class")
class_dict[2]=ClassTest()
for key in class_dict:
   print "%d  %15s, %3d, %s" % (key, class_dict[key].field1, \
          class_dict[key].field2, class_dict[key].field3)
print

class_dict[2].field2=99
class_dict[1].chg_field1("Field 1 changed")
for key in class_dict:
   print "%d  %15s, %3d, %s" % (key, class_dict[key].field1, \
          class_dict[key].field2, class_dict[key].field3)

You could simply use a list to store the class instances. Now the index of the list would be your fragment number.

Python3 also offers named tuples.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.