21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Classes 115

métodos e atributos novos, por exemplo. A mesma lógica se aplica aos

objetos.

Exemplo de como acrescentar um novo método:

# -*- coding: latin1 -*-

class User(object):

"""Uma classe bem simples.

"""

def __init__(self, name):

"""Inicializa a classe, atribuindo um nome

"""

self.name = name

# Um novo método para a classe

def set_password(self, password):

"""Troca a senha

"""

self.password = password

print 'Classe original:', dir(User)

# O novo método é inserido na classe

User.set_password = set_password

print 'Classe modificada:', dir(User)

user = User('guest')

user.set_password('guest')

print 'Objeto:', dir(user)

print 'Senha:', user.password

Saída:

Classe original: ['__class__', '__delattr__', '__dict__', '__doc__',

'__getattribute__', '__hash__', '__init__', '__module__', '__new__',

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',

'__weakref__']

Classe modificada: ['__class__', '__delattr__', '__dict__', '__doc__',

'__getattribute__', '__hash__', '__init__', '__module__', '__new__',

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',

'__weakref__', 'set_password']

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!