1
I am starting to work with Python and saw that there is no way to create multiple constructors in the same class. With that I thought I’d move on to the constructor __init__
an object containing class attributes, as in the example:
class Foo(object):
'''
classdocs
'''
_id = None
name = None
def __init__(self, *attrs):
if attrs:
for key, value in attrs.iteritems():
setattr(self, key, value)
def __getattr__(self, key):
if(hasattr(self, key)):
return key
else:
return None
def __setattr__(self, k, v):
if hasattr(self, k):
super().__setattr__(k, v)
return True
else:
return False
The problem is that I am not managing to feed my class with the existing attributes, always presents a mistake. When I create a simple class instance without passing attributes and manually define attributes, the class also does not restrict if it does not exist.
from Project.Models.Foo import Foo
c = Foo()
print(c._id)
print(c.name)
print(c.foo)
In doing so I have the error:
Traceback (most recent call last):
File "F:\Project\src\Project\Test\TestFoo.py", line 7, in <module>
print(c.foo)
File "F:\Project\src\Project\Models\Foo.py", line 25, in __getattr__
if(hasattr(self, key)):
Does anyone have an idea of how I can pass objects to set classes and how I can restrict the get and set if the attribute does not exist?
Cara had already forgotten this question but it certainly solves the problem I had, thank you very much!
– LeandroLuk