Skip to content

Instantly share code, notes, and snippets.

@britodfbr
Created July 17, 2017 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save britodfbr/0df2b3ce052fa1564dbf9fe5d8f4671e to your computer and use it in GitHub Desktop.
Save britodfbr/0df2b3ce052fa1564dbf9fe5d8f4671e to your computer and use it in GitHub Desktop.
Atributos dinamicos para classes
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()
uso()
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()
uso()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment