Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
Add Properties to Instances?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Jeremy Bowers, post: 1809358"] I'm going to echo Steven's comment: "What's the situation in which you think you want different properties for different instances of the same class?" Another thought would be a custom __setattr__ and a bit of support: Python 2.3.5 (#1, Mar 3 2005, 17:32:12) [GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information..... def __init__(self): .... self.__dict__['_readOnly'] = sets.Set() .... def addReadOnly(self, key, value): .... setattr(self, key, value) .... self._readOnly.add(key) .... def __setattr__(self, key, value): .... if key in self._readOnly: .... raise AttributeError("can't set attribute") .... self.__dict__[key] = value .... Traceback (most recent call last): File "<stdin>", line 1, in ? Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 5, in addReadOnly I don't guarantee this completely fits the bill but I'm sure you can adapt it from here. Also note that, strictly speaking, you can't make a "true" read-only attribute, only one that alerts a programmer if they try the simple way. In a pure-Python object, there is always a way in. This shouldn't worry you if you're using Python ("We're all consenting adults here"), but you should also be aware of that. That said, this is certainly useful in the real world. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
Add Properties to Instances?
Top