Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
atributos dinamicos em classes Python
class Foo:
'''
classdocs
>>> f = Foo()
>>> f.nome = 'nome'
>>> f.nome
'nome'
>>> f._id = 1
>>> f._id
1
>>> f.foo = Foo
>>> f.foo
<class '__main__.Foo'>
'''
_id = None
name = None
def __init__(self, **attrs):
if attrs:
for key, value in attrs.items():
setattr(self, key, value)
def __getattr__(self, key):
if key in self.__dict__:
return self.__dict__[key]
return None
def __setattr__(self, k, v):
if hasattr(self, k):
super().__setattr__(k, v)
return True
return False
@staticmethod
def uso():
g = Foo(_id=0, name='asdf', foo=None)
print(g._id)
print(g.name)
print(g.foo)
if __name__ == '__main__':
import doctest
doctest.testmod()
Foo.uso()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment