Created
July 17, 2017 14:48
-
-
Save britodfbr/0df2b3ce052fa1564dbf9fe5d8f4671e to your computer and use it in GitHub Desktop.
Atributos dinamicos para classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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