Created
December 11, 2011 05:24
-
-
Save gustavofonseca/1458570 to your computer and use it in GitHub Desktop.
descritores leitura e escrita sem passar o nome do atributo
This file contains hidden or 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
#!/usr/bin/env python | |
# coding:utf-8 | |
""" | |
>>> livro = Livro('Eram os deuses astronautas?', 'Erich von Daniken') | |
>>> livro.autor_individual | |
'DANIKEN, Erich von' | |
>>> livro2 = Livro('O menino maluquinho', 'Ziraldo') | |
Traceback (most recent call last): | |
... | |
ValueError: Deve ser informado o nome e sobrenome | |
""" | |
class Autor(object): | |
def __set__(self, instancia, valor): | |
if len(valor.split()) < 2: | |
raise ValueError('Deve ser informado o nome e sobrenome') | |
for nome_atr, valor_atr in instancia.__class__.__dict__.items(): | |
if valor_atr == self: | |
self.nome_atr = '__'+nome_atr | |
setattr(instancia, self.nome_atr, valor) | |
def __get__(self, instancia, classe): | |
desmontado = getattr(instancia, self.nome_atr).split() | |
sobrenome = desmontado[-1] | |
restante = ' '.join(desmontado[:-1]) | |
return '%s, %s' % (sobrenome.upper(), restante) | |
class Livro(object): | |
autor_individual = Autor() | |
def __init__(self, titulo, autor_individual): | |
self.titulo = titulo | |
self.autor_individual = autor_individual | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment