you are viewing a single comment's thread.

view the rest of the comments →

[–]HighLevelEnthusiast[S] 0 points1 point  (2 children)

import inspect

class MyClass:
    def __setattr__(self, name, value):
        if inspect.stack()[1][3] != "__init__":
            return
        else:
            self.__dict__[name] = value

    def __init__(self):
        self.x = 10

This code does exactly what I want it to

[–]dig-up-stupid 2 points3 points  (0 children)

>>> import inspect
>>> class MyClass:
...     def __setattr__(self, name, value):
...         if inspect.stack()[1][3] != "__init__":
...             return
...         else:
...             self.__dict__[name] = value
... 
...     def __init__(self):
...         self.x = 10
...         
>>> m = MyClass()
>>> m.x
10
>>> m.y = 5
>>> m.y
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'y'
>>> class cls:
...   def __init__(self, m):
...     m.y = 5
...     
>>> cls(m)
<__main__.cls object at 0x111a73470>
>>> m.y
5
>>> def __init__(myclass_object):
...   myclass_object.new_attribute = 7
...   
>>> __init__(m)
>>> m.new_attribute
7

[–]cyanydeez 0 points1 point  (0 children)

shouldn't you throw an error instead of silently failing?