Programação Orientada a Objetos Intermediária em Python
Jake Roach
Data Engineer
class Student:
# Lógica condicional com comportamento semelhante em todas as condições
def explore_topic(self, resource_type, topic):
if resource_type == "Textbook":
print(f"Referencing {topic} using a textbook")
self.reference_textbook(topic)
elif resource_type == "Blog":
print(f"Make sure to validate information provided in blogs!")
self.reference_blog(topic)
elif resource_type == "Video":
self.reference_video(topic)
Padrão de projeto que usa métodos de fábrica para criar objetos usados em outro método
_ para indicar um método de fábrica$$
Primeiro, vamos ver produtos e produtos concretos!
...
def _get_resource(self, resource_type):
if resource_type == "Textbook":
# Textbook, Blog and Video are
# all resources
return Textbook()
elif resource_type == "Blog":
return Blog()
elif resource_type == "Video":
return Video()
class Resource(ABC):
@abstractmethod
def reference(self, topic):
pass
class Textbook(Resource):
def __init__(self):
self.index = {"Object-oriented Programming": ["Inheritance", ...]}
def reference(self, topic):
print(f"Referencing {topic} using a textbook")
return self.index.get(topic)
# Algo semelhante para Blog, Video
class Student:
def explore_topic(self, resource_type, topic):
if resource_type == "Textbook":
texbook = Textbook() # Criando uma instância de classe que implementa Resource
texbook.reference(topic) # Chamar o método reference()
elif resource_type == "Blog":
blog = Blog()
blog.reference(topic)
elif resource_type == "Video":
video = Video()
video.reference(topic)
class Student:
# Método de fábrica que retorna Resource
def _get_resource(self, resource_type):
if resource_type == "Textbook":
return Textbook()
elif resource_type == "Blog":
return Blog()
elif resource_type == "Video":
return Video()
def explore_topic(self, resource_type, topic):
resource = self._get_resource(resource_type) # Obter o recurso
return resource.reference(topic)
# Crie um objeto Student e use-o para consultar um livro-texto
lester = Student()
lester.explore_topic("Textbook", "Object-oriented Programming")
# Depois, troque para outro recurso
lester.explore_topic("Video", "Object-oriented Programming")
Referencing Object-oriented Programming using a textbook
["Inheritance", "Constructors", "Class-level methods"]
Video are helpful for visual or audatory learners
["Classes", "Methods", "Attributes", "self"]
Programação Orientada a Objetos Intermediária em Python