Python @ DjangoSpin

Object Oriented Python: Creating random objects of subclasses of a superclass

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Creating random objects of subclasses of a superclass in Python

Creating random objects of subclasses of a superclass in Python

Using the random module and Generators, we can have Python make random objects of subclasses of a superclass.

>>> import random
>>> class Crop(object):
	def sow(self):
		print("Sowing...")
	def irrigate(self):
		print("Irrigating...")
	def harvest(self):
		print("Harvesting...")

		
>>> class Wheat(Crop): pass

>>> class Corn(Crop): pass

>>> class Tomato(Crop): pass

>>> def cropGenerator(numberOfInstancesToCreate):
    crops = Crop.__subclasses__()
    for number in range(numberOfInstancesToCreate):
        yield random.choice(crops)()

        
>>> cropGeneratorObject = cropGenerator(5)
>>> for cropObject in cropGeneratorObject:
	print(cropObject)

	
<__main__.Corn object at 0x02E7E950>
<__main__.Corn object at 0x02E65BB0>
<__main__.Wheat object at 0x02B09EB0>
<__main__.Tomato object at 0x02E65BB0>
<__main__.Corn object at 0x02B09EB0>

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply