Reputation: 391
I am in a situation where the structure returned by a function will likely not need to be used anywhere outside of that function. However since it's not a simple value but an actual object I would like to declare a class inside my function that I can instantiate then return.
eg:
def CreateSomeFunkyDataStructure():
class FunkyClass:
def __init__(self):
self.var1 = 'Play that funky music white boy.'
def getFunky(self):
print 'Play that funky music right.'
x = FunkyClass()
return x
o = CreateSomeFunkyDataStructure()
print o.var1
o.getFunky()
My question is whether this is a good practice or a bad one since this just feels strange. At the same time it seems to me that because the purpose of encapsulation is to prevent someone from accessing the implementation of a function, in this case it might be quite appropriate. If the class is not something that will be required anywhere else in the program, there is no reason for the rest of the program to have access to it.
Upvotes: 3
Views: 2086
Reputation: 97601
This is bad because it makes the following break:
isinstance(result, FunkyClass)
CreateSomeFunkyDataStructure
multiple times will not even be of the same type! (ie, type(f1) is not type(f2)
)map(FunkyClass.getFunky, [funcy1, funcy2])
pickle
ingUpvotes: 5