Inheritance & encapsulation · Herança e encapsulamento
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
Construir sobre uma classe existente
- Herança permite que uma nova classe reutilize uma existente.
- A nova classe é a subclasse (filho); a original é a superclasse (pai).
- Escreva
class Bird(Animal):—Birdobtém todos os métodos deAnimal. (Na pseudocódigo do exame:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
Chame o pai com super()
- Uma subclasse pode adicionar seus próprios atributos em
__init__. - Use
super().__init__(...)para executar primeiro o__init__do pai. - Isso evita repetir o código de configuração do pai.
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
Sobrescrever um método
- Uma subclasse pode sobrescrever um método: definir um com o mesmo nome.
- A versão da subclasse é usada em vez da do pai.
- Isso permite que cada classe se comporte de maneira única.
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
Encapsulamento
- Encapsulamento significa manter os dados de um objeto seguros dentro dele.
- Python não tem realmente "privado", mas um underline inicial (
self._balance) sinaliza "não tocar de fora". - Outro código deve usar métodos para ler ou alterar os dados, em vez de acessar diretamente.
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
Polimorfismo
- Polimorfismo significa um único nome de método, mas comportamento diferente por classe.
- Um loop pode chamar
.speak()em muitos objetos sem saber seu tipo exato. - Cada objeto responde de sua própria maneira.
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
Erros comuns
- Uma subclasse herda de seu pai e pode adicionar ou sobrescrever métodos.
- Mantenha os dados privados e acesse-os através de métodos (encapsulamento).
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
Agora você tenta
- Use herança, sobrescrita, encapsulamento e chame métodos em diferentes objetos.
- Clique em Check answer para testar seu código.
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · A classe Animal é dada. Escreva uma subclasse Cat(Animal) que herde dela e adicione um método speak(self) retornando "Meow". (Ela ainda deve ter o name_is herdado.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
The class Shape is given (its area returns · decrescentes 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · A classe Shape é dada (seu area retorna 0). Escreva Square(Shape): seu __init__(self, side) deve chamar super().__init__("square"), armazenar side, e sobrescrever area para retornar side * side.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Classes Dog and · e Cat are given, each with a speak(). Write speak_all(animals) that returns · decrescentes a list of each animal's speak() result, in order. · As classes Dog e Cat são dadas, cada uma com um speak(). Escreva speak_all(animals) que retorna uma lista do resultado de cada animal speak(), em ordem.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a class Account whose __init__(self) sets a private balance · saldo self._balance to · até 0. Add deposit(self, amount) to add to it, and balance(self) to · até return · retorno it. Other code should use these methods, not touch _balance directly. · Escreva uma classe Account cujo __init__(self) define um saldo privado self._balance como 0. Adicione deposit(self, amount) para adicionar a ele, e balance(self) para retornar ele. Outro código deve usar esses métodos, não tocar _balance diretamente.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.