[Tutor] how to create a generic instance of an object?

Jacob S. keridee at jayco.net
Fri Sep 16 03:05:14 CEST 2005


Two further suggestions.

1) Do you believe each class have to be in a seperate file? Is that habit 
from Perl?
    Try putting each class in one library file and then importing as 
needed/all into main script to be used
    as desired, maybe coexistent with the dictionary approach mentioned

2) How about a package? Except... that's kinda similar to the choice one...

Oh well, Danny's works -- 

Jacob


> I've got a base class "Asset", and currently have about 20 sub-classes
> (assetTypes) that will inherit from it, with more to follow, I'm sure.
> All of the assetTypes will have the same methods, but they'll be
> polymorphic; each assetType's methodA() will do something slightly
> different from it's sibling assetTypes.
>
> What I want to do is to pass in the assetType at runTime via an external
> script, create a new instance of it, and then run that instance's
> methods.  That way I won't have to have 20 or more " if assetType== "
> if/elif statements, and maintaining the script that creates new
> instances won't become a nightmare.
>
> And changing the base class' __init__ to contain another if/elif every
> time someone adds another assetType seems to be so wrong, I rejected
> that approach out of hand.  I want to design this thing so that the base
> class doesn't need to know about all the sub-classes.
>
> Perhaps I'm taking the wrong approach here with the Asset/AssetType
> base-class/sub-class organization; it's beginning to feel that way.
>
> I've tried something like this:
>
> <asset.py>
> class Asset: pass
>
> <foo.py>
> class Foo(Asset): pass
>
> <script.py>
> from asset import Asset
> from foo import Foo
>
> klass = 'Foo'
> o = klass()
>
> which gets me 'string not callable', which is kind of expected.
>
> On p.325 of the O'Reilly Learning Python (2nd ed.), there's an example
> of generic instance creation, but the values passed in are class
> objects, not strings...  I'm guessing that this works because it's all
> in the same module, so it knows that the things in the tuple iterated
> over in the foreach are classes.
>
> Any ideas?  I'm an old hand at perl (10+ years), but very new to Python,
> so please be patient.
>
> John Burk
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list