Movatterモバイル変換


[0]ホーム

URL:


Class Variable Question

Bob Klinebkline at rksystems.com
Mon Apr 9 13:48:55 EDT 2001


On Mon, 9 Apr 2001, Alex Martelli wrote:> "Robert Johnson" <rjohnson at exotic-eo.com> wrote in message> news:3ad1c7e9$0$196$e2e8da3 at nntp.cts.com...>> > Is there a way to prevent this so users cannot add variables?>> Nope (how would one distinguish 'users' from other pieces> of code for this purpose?).  You can wrap objects up into> a Bastion if you have security worries.>> > It seems to me that the user could just override a class with> > unrelated data.>> Sure, just like he could say x=y-z when actually meaning x=y+z, and> a zillion other horrible programming errors.>> Hopefully the user will then run some _tests_ (what other ways would> you suggest for the "plus oops I meant minus" kind or errors to be> caught...?), fix the mistakes he then finds as a result of his> testing, and have code with fewer errors -- including code free from> accidental, erroneous rebindings of all kinds.Ah, you have to love these "You-mean-you-actually-put-bugs-in-your-software-that-you-have-difficulty-finding?" responses, especially whenthe alternating refrain from Python fans is "Why on earth would you wantto use a language which doesn't eliminate memory management bugs foryou?"And now for something completely different.  Here's a (possibly) morehelpful response.  You might want to try something along these lines:$ cat SafeClass.pyclass SafeClass:    members = ('foo','bar')    def __init__(self):        self.foo = 42        self.bar = 'floccinaucinihilipilification'    def __setattr__(self, name, value):        if name not in SafeClass.members:            raise "%s is not a member of SafeClass" % name        self.__dict__[name] = value$ pythonPython 1.5.2 (#1, Aug 25 2000, 09:33:37)  [GCC 2.96 20000731 (experimental)] on linux-i386Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam>>> from SafeClass import SafeClass>>> sc = SafeClass()>>> sc.foo = 43>>> sc.fud = 44Traceback (innermost last):  File "<stdin>", line 1, in ?  File "SafeClass.py", line 5, in __setattr__    raise ("%s is not a member of SafeClass" % (name,))fud is not a member of SafeClassAs you can see, this approach needs another five lines in the classdefinition, and of course the members list would have to be maintained,but the example demonstrates that the correct answer to your question("Is there a way to prevent this so users cannot add variables?") isactually "Yes."  The approach doesn't prevent intentional undermining ofthe safety measure, but it will catch the sorts of mistakes you'reasking about.Hope this helps.-- Bob Klinemailto:bkline at rksystems.comhttp://www.rksystems.com


More information about the Python-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp