I am currently doing this, to do different things based on an object's type:
actions = {
SomeClass: lambda: obj.name
AnotherClass: lambda: self.normalize(obj.identifier)
...[5 more of these]...
}
for a in actions.keys():
if isinstance(obj, a):
return actions[a]()
Is it possible to cut out the for loop, and do something like this?
actions[something to do with obj]()
class SomeClass( object ):
....
def action( self ):
return self.name
class AnotherClass( object ):
....
def action( self ):
return self.normalize( self.identifier )
[5 more classes like the above two]
a.action()
Simpler. Clearer. More extensible. Less Magic. No dictionary. No loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With