crislanio_macedo Posted November 29, 2015 at 05:47 PM Report #590209 Posted November 29, 2015 at 05:47 PM (edited) Olá a todos, sou iniciante e estou começando a aprender python. Me deparei com um erro simples mas que gostaria de uma explicação mais sucinta. class Animal: __name = "" __sound = 0 def __init__ (self, name, sound): self.__name = name self.__sound = sound def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_sound(self, sound): self.__sound = sound def get_sound(self): return self.__sound def get_type (self): print ("Animal") def to_string (self): return "{} com som {} " .format(self.__name, self.__sound) cat = Animal('XXX', 'Meow') print (cat.to_string()) class Dog(Animal): __owner = "" def __init__(self, name, sound, owner): self.__owner = owner super(Dog, self).__init__(name, sound) def set_owner(self, owner): self.__owner= owner def get_owner(self): return self.owner def get_type (self): print ("Dog") def to_string (self): return "{} com som {} ele eh {} " .format(self.__name, self.__sound, self.__owner) def multiple_sounds (self, how_many=None): if how_many is None: print (self.get_sound()) else: print(self.get_sound() * how_many) spot = Dog ("Spot", "Ruff", "Joao") print (spot.to_string()) class AnimalTesting: def get_type(self, animal): animal.get_type() test_animals = AnimalTesting() test_animals.get_type(cat) test_animals.get_type(spot) spot.multiplos_sons(4) spot.multiplos_sons() O erro foi: Traceback (most recent call last): File "ex.py", line 53, in spot = Dog ("Spot", "Ruff", "Joao") File "ex.py", line 33, in __init__ super(Dog, self).__init__(name, sound) TypeError: must be type, not classobj Desde já agradeço a discussão. Edited November 29, 2015 at 05:53 PM by crislanio_macedo
Solution pwseo Posted November 29, 2015 at 09:38 PM Solution Report #590222 Posted November 29, 2015 at 09:38 PM crislanio_macedo, O erro que referes não acontece se estiveres a utilizar Python 3.x. Isto deve-se ao facto de que só podes utilizar super() com new-style classes, que é a opção pré-definida na versão 3.x. No Python 2.x tens que especificar isso herdando de object: # Funciona em Python 2 e 3 class Animal(object): # ... Corrigindo isso (ou correndo inicialmente no Python 3) vai reparar que há outro erro: XXX com som Meow Traceback (most recent call last): File "cris.py", line 57, in <module> print (spot.to_string()) File "cris.py", line 47, in to_string return "{} com som {} ele eh {} ".format(2, self.__sound, self.__owner) AttributeError: 'Dog' object has no attribute '_Dog__sound' Como podes reparar, a primeira linha (referente ao gato) apareceu, mas há um erro estranho no que diz respeito ao nome do cão. Isto tem a ver com alterações feitas aos nomes para evitar problemas ao herdar de uma classe: todos os atributos com nomes com a forma __bla são alterados para _Classname__bla (daí o _Dog__name). Uma solução será utilizares os acessores que criaste (get__name(), get__sound()) ou utilizar variáveis com nomes que não comecem por __. Corrigido isto, surge ainda: XXX com som Meow Spot com som Ruff ele eh Joao Animal Dog Traceback (most recent call last): File "cris.py", line 67, in <module> spot.multiplos_sons(4) AttributeError: 'Dog' object has no attribute 'multiplos_sons' Este erro é mais fácil de corrigir: tu definiste multiple__sounds mas estás a tentar invocar multiplos_sons. Penso que era tudo: ~ $ python crislanio.py XXX com som Meow Spot com som Ruff ele eh Joao Animal Dog RuffRuffRuffRuff Ruff
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now