我试图在python类中获得具有很多关系的想法,虽然理论上我理解了这个概念,但是当我尝试实现它时,却没有得到正确的输出:
代码:
## Animal is-a object
class Animal(object):
def sound(str):
print("sound of animals")
## Dog is-a Animal, Dag has a name
class Dog(Animal):
"""docstring for Dog."""
def __init__(self, name):
#super(Dog, self).__init__()
#initializing dog name
self.name = name
def sound(str):
print("Dog barks")
## Cat is-a animal, Cat also has a name
class Cat(Animal):
"""docstring for Cat."""
def __init__(self, name):
# initializing cat name
self.name = name
def sound(str):
print("Cat meows")
## Person has-a pet of some kind
## Person is-a object
class Person(object):
"""docstring for Person."""
def __init__(self, name):
#super(Person, self).__init__()
self.name = name
## Person has-a pet of some kind
self.pet = None
## rover is-a dog
rover = Dog("Rover")
rover.sound()
## Satan is-a cat
satan = Cat("Satan")
tiger = Cat("tiger")
satan.sound()
## Mary is-a Person
Mary = Person("Mary")
Mary.pets = [satan ,tiger , rover ] # list of pets
Mary.pets ={'cats' : [satan, tiger] , 'dogs': [rover]} #dictionary of lists of pets
print("No. of pets mary has ")
for x,y in Mary.pets.items():
print(x, ":" , y)
从对象获取所有字典值的语法是否正确:
for x,y in Mary.pets.items():
print(x, ":" , y)
我得到以下输出:
Dog barks
Cat meows
No of pets mary has
cats : [<__main__.Cat object at 0x011F0D30>, <__main__.Cat object at 0x011F0CF0>]
dogs : [<__main__.Dog object at 0x011F0CD0>]
为什么我得到地址而不是价值?
答案 0 :(得分:0)
请参见下文
name属性保留在基类上。基类也实现 repr
## Animal is-a object
class Animal(object):
def __init__(self,name):
self.name = name
def sound(str):
print("sound of animals")
def __repr__(self):
return self.name
## Dog is-a Animal, Dag has a name
class Dog(Animal):
"""docstring for Dog."""
def __init__(self, name):
super(Dog, self).__init__(name)
def sound(str):
print("Dog barks")
## Cat is-a animal, Cat also has a name
class Cat(Animal):
"""docstring for Cat."""
def __init__(self, name):
super(Cat, self).__init__(name)
def sound(str):
print("Cat meows")
## Person has-a pet of some kind
## Person is-a object
class Person(object):
"""docstring for Person."""
def __init__(self, name):
#super(Person, self).__init__()
self.name = name
## Person has-a pet of some kind
self.pet = None
## rover is-a dog
rover = Dog("Rover")
rover.sound()
## Satan is-a cat
satan = Cat("Satan")
tiger = Cat("tiger")
satan.sound()
## Mary is-a Person
Mary = Person("Mary")
Mary.pets = [satan ,tiger , rover ] # list of pets
Mary.pets ={'cats' : [satan, tiger] , 'dogs': [rover]} #dictionary of lists of pets
print("No. of pets mary has ")
for x,y in Mary.pets.items():
print(x, ":" , y)
输出
Dog barks
Cat meows
No. of pets mary has
('cats', ':', [Satan, tiger])
('dogs', ':', [Rover])