Anda di halaman 1dari 25

CES 22 aula 5

Decoradores, mtodos estticos e de classe, classes abstratas


Objetivos
Decoradores
Mtodos estticos
Mtodos de classe
Classes abstratas e interfaces
Decoradores
#Funcoes podem ser atribuidas a variaveis

def greet(name):
return "hello "+name
greet_someone = greet
print (greet_someone("John"))

# Outputs: hello John

#Funcoes podem ser declaradas dentro de funcoes

def greet(name):
def get_message():
return "Hello "
result = get_message()+name
return result
print (greet("John") )
# Outputs: Hello John
# funcoes podem ser passadas como parametros para
outras funcoes

def greet(name):
return "Hello " + name
def call_func(func):
other_name = "John"
return func(other_name)
print (call_func(greet))
# Outputs: Hello John

#funcoes podem retornar outras funcoes

def compose_greet_func():
def get_message():
return "Hello there!"
return get_message
greet = compose_greet_func()
print (greet() )
# Outputs: Hello there!
#funcoes internas possuem acesso de leitura para o
escopo externo
# Esta propriedade conhecida como fechamento
(Closure)

def compose_greet_func(name):
def get_message():
return "Hello there "+name+"!
return get_message
greet = compose_greet_func("John")
print (greet() )
# Outputs: Hello there John!
Decoradores so embrulhos (Wrappers) para funes

def get_text(name):
return "lorem ipsum, {0} dolor sit
amet".format(name)

def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper

my_get_text = p_decorate(get_text)
print (my_get_text("John") )
# <p>Outputs lorem ipsum, John dolor sit
amet</p>
get_text = p_decorate(get_text)
print (get_text("John"))
# Outputs lorem ipsum, John dolor sit
amet

def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))

return func_wrapper

@p_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit
amet".format(name)

print (get_text("John"))

# Outputs <p>lorem ipsum, John dolor sit


def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper

def strong_decorate(func):
def func_wrapper(name):
return
"<strong>{0}</strong>".format(func(name))
return func_wrapper

def div_decorate(func):
def func_wrapper(name):
return
"<div>{0}</div>".format(func(name))
return func_wrapper

get_text = div_decorate(p_decorate(strong_decorate(get_text)))
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")

# Outputs <div><p><strong>lorem ipsum, John dolor sit


amet</strong></p></div>
def p_decorate(func):
def func_wrapper(self):
return
"<p>{0}</p>".format(func(self))
return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"

@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()
print (my_person.get_fullname())
def p_decorate(func):
def func_wrapper(*args, **kwargs):
return "<p>{0}</p>".format(func(*args, **kwargs))
return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"

@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()

print (my_person.get_fullname())
def tags(tag_name):
def tags_decorator(func):
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name,
func(name))
return func_wrapper
return tags_decorator

@tags("p")
def get_text(name):
return "Hello "+name

print (get_text("John"))

# Outputs <p>Hello John</p>


Mtodos estticos e de classe
>>> class Pizza(object):
... def __init__(self, size):
... self.size = size
... def get_size(self):
... return self.size
...
>>> Pizza.get_size
<unbound method Pizza.get_size>

>>> Pizza.get_size(Pizza(42))
42

>>> Pizza(42).get_size()
42
Mtodos estticos
class Pizza(object):
@staticmethod
def mix_ingredients(x, y):
return x + y

def cook(self):
return self.mix_ingredients(self.cheese,
self.vegetables)
>>> Pizza().cook is Pizza().cook
False
>>> Pizza().mix_ingredients is Pizza.mix_ingredients
True
>>> Pizza().mix_ingredients is Pizza().mix_ingredients
True
Mtodos de classe
>>> class Pizza(object):
... radius = 42
... @classmethod
... def get_radius(cls):
... return cls.radius
...
>>>
>>> Pizza.get_radius
<bound method type.get_radius of <class '__main__.Pizza'>>
>>> Pizza().get_radius
<bound method type.get_radius of <class '__main__.Pizza'>>
>>> Pizza.get_radius is Pizza().get_radius
True
>>> Pizza.get_radius()
42
class Pizza(object):
def __init__(self, ingredients):
self.ingredients = ingredients

@classmethod
def from_fridge(cls, fridge):
return cls(fridge.get_cheese() +
fridge.get_vegetables())
class Pizza(object):
def __init__(self, radius, height):
self.radius = radius
self.height = height

@staticmethod
def compute_area(radius):
return math.pi * (radius ** 2)

@classmethod
def compute_volume(cls, height, radius):
return height * cls.compute_area(radius)

def get_volume(self):
return self.compute_volume(self.height, self.radius)
Mtodos abstratos

# the simplest way to write an abstract method in


Python is:

class Pizza(object):
def get_radius(self):
raise NotImplementedError

oblema: Se for criada uma subclasse de Pizza e for esquecido a implementao


get_radius, o erro somente ser descoberto quando o mtodo for executado.
import abc

class BasePizza(object):
__metaclass__ = abc.ABCMeta

@abc.abstractmethod
def get_radius(self):
"""Method that should do
something."""

>>> BasePizza()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class BasePizza with abstract
methods get_radius
import abc

class BasePizza(object):
__metaclass__ = abc.ABCMeta

@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""

class Calzone(BasePizza):
def get_ingredients(self, with_egg=False):
egg = Egg() if with_egg else None
return self.ingredients + egg
import abc

class BasePizza(object):
__metaclass__ = abc.ABCMeta

@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""

class DietPizza(BasePizza):
@staticmethod
def get_ingredients():
return None
import abc

class BasePizza(object):
__metaclass__ = abc.ABCMeta

ingredient = ['cheese']

@classmethod
@abc.abstractmethod
def get_ingredients(cls):
"""Returns the ingredient list."""
return cls.ingredients
import abc

class BasePizza(object):
__metaclass__ = abc.ABCMeta

default_ingredients = ['cheese']

@classmethod
@abc.abstractmethod
def get_ingredients(cls):
"""Returns the ingredient list."""
return cls.default_ingredients

class DietPizza(BasePizza):
def get_ingredients(self):
return ['egg'] + super(DietPizza, self).get_ingredients()
Referencias
http://thecodeship.com/patterns/guide-to-
python-function-decorators/
https://julien.danjou.info/blog/2013/guide-
python-static-class-abstract-methods
Exerccios
Desenvolva um exemplo de funo com *args
e **kargs.
Pesquise sobre decoradores em Python e crie
um exemplo com decoradores no vistos em
sala.
Crie um exemplo usando classes abstratas,
mtodos estticos e mtodos de classe.

Anda mungkin juga menyukai