I have a domain object User
. I am looking for some way to restrict other python classes form creating any objects of `user' type.
Asked
Active
Viewed 133 times
-2

Pratik
- 30,639
- 18
- 84
- 159

Vijay Shanker Dubey
- 4,308
- 6
- 32
- 49
-
1Do you mean you want to create a singleton User object? Singleton: http://en.wikipedia.org/wiki/Singleton_pattern – amit kumar Sep 27 '11 at 09:25
-
4There is always a way. Write it in the docs. – rplnt Sep 27 '11 at 09:26
-
No, not singleton. But The object should be created by some global method in the module only. If possible, I have very little knowledge about Python – Vijay Shanker Dubey Sep 27 '11 at 09:27
-
1Have a look at http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private – ThiefMaster Sep 27 '11 at 09:28
1 Answers
1
You can use closures to hide the object away from the code but please accept that doing it in Python is considered very unpythonic and is pretty much against the philosophy of the language. You are supposed to document proper behavior, not guard against your users.
class KittenFactory(object):
def __create_teh_secret_objectz(self):
class Kitten(object):
i_can_haz_invisible = True
return Kitten()
Willing programmers will still be able to either copy()
it or get its type()
and instantiate it manually.
In other words: don't go there.

patrys
- 2,729
- 17
- 27