我正在上课关于课程:
http://learnpythonthehardway.org/book/ex42.html
我有80-90%的理解它是如何工作的,我正在玩代码使它做其他事情我试图得到一个句子打印出来的说明如下:
'玛丽有一只被称为撒旦的猫
我的理解是Python会继承下面的所有3个类来打印出这个语句,但是我不能打印它只打印我想要的东西:
'Mary在0x000000000569B0B8>处有一个< main .Cat对象。名为< main .Cat对象位于0x000000000569B0B8>'
所以它打印出字符串然后是实际的Python对象,而不是它们是什么?
这是下面的代码,对不起它并且还有其他一些事情在进行,但我想我需要向所有人展示一下,了解最新情况?
这就是我坚持的路线:
def has_pet(self): print self.name,“has a”,self.pet,“called”,satan
我看不出我做错了什么:/
class Animal(object):
def __init__(self, species):
self.species = species
def print_animal(self):
print "This is a ", self.species, ", it croaks"
class Dog(Animal):
def __init__(self, dog_name, species):
## Dog has a name that is name
self.dog_name = dog_name
self.species = species
def print_name(self):
print "The pet is called...", self.dog_name
def print_species(self):
print "Your pet is a ", self.species
def ask_dog(self):
print "What kind of dog do you have?"
choice = raw_input("> ")
print "Oh wow, I have a ", choice, " too"
yourDog = Dog("Bob", "dog")
yourAnimal = Animal('frog')
yourAnimal.print_animal()
yourDog.print_name()
yourDog.print_species()
yourDog.ask_dog()
class Cat(Animal):
def __init__(self, name):
## Cat has a name that is name
self.name = name
self.species = 'Cat' #is this redundant?
def print_name(self):
print "The cat is called ", self.name
your_cat = Cat('Tigger')
your_cat.print_name()
class Person(object):
def __init__(self, name):
## Person has a name that is name
self.name = name
## Person has-a pet of some kind
self.pet = satan
def has_pet(self):
print self.name, " has a ", self.pet, " called", satan #stuck here
## satan is-a Cat
## Cat is-aanimal
## animal is-a object
satan = Cat("Satan")
satan.print_name()
## mary is-a Person
## Person is-a object
who = Person("Mary")
who.has_pet()
答案 0 :(得分:1)
是的,当你尝试在python中打印出一个对象时,python内部调用它的__str__
方法,如果你的类中没有直接定义__str__
方法,那么它会尝试从一个超类的默认情况下,如果没有指定超类,object
类将成为您类的超类,并且它具有打印出来的__str__
实现 - <main.Cat object at 0x000000000569B0B8>
。
显示 -
的示例>>> object.__str__(object())
'<object object at 0x003E1490>'
现在,这就是你得到<main.Cat ....>
的原因,我相信你不想直接打印出对象,而应该访问对象中的name变量并将其打印出来并访问{{ 1}}变量并打印出来。
示例有问题的行将更改为 -
species