我正在经历LPTHW并且在前42(http://learnpythonthehardway.org/book/ex43.html),我认为我对is-a和has-a概念有一个很好的把握,但在研究演习中他要求我们添加列表并且对类进行了说明,使其成为一个功能更强大的脚本。我想为狗或猫添加一个列表给个人或员工,以便存储姓名的值和员工的工资情况。我不知道如何做到这一点,并使其功能,有人可以给我一个简短的例子,我想要做什么,我将从那里建立完成其余的。谢谢,下面还有代码......
我所得到的简单例子......
class Animal(object):
pass
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
##Dog has-a name
self.name = name
self.doglist = []
Dog.doglist.append("Rover")
当我执行上述操作时,我收到错误'AttributeError:type object'Dog'没有属性doglist。
完整代码:
##Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
##Dog has-a name
self.name = name
##Cat is-a animal
class Cat(Animal):
def __init__(self, name):
##Cat has-a name
self.name = name
##Person is-a object
class Person(object):
def __init__(self, name):
##Person has-a name
self.name = name
##Person has-a pet
self.pet = None
##Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## not sure what this does
super(Employee, self).__init__(name)
##Person has-a salary
self.salary = salary
##Fish is a class
class Fish(object):
pass
##Salmon is-a fish and is a class
class Salmon(Fish):
pass
##Halibut is-a fish
class Halibut(Fish):
pass
##rover is-a Dog
rover = Dog("Rover")
##satan is-a Cat
satan = Cat("Satan")
##mary is a person
mary = Person("Mary")
##Mary has-a pet named satan
mary.pet = satan
##frank is-a employee that has-a salary of 120,000
frank = Employee("Frank", 120000)
##frank has-a pet rover(dog)
frank.pet = rover
##flipper is-a instance of Fish
flipper = Fish()
##crouse is-a instance of salmon
crouse = Salmon()
##harry is-a instance of Halibut
harry = Halibut()
print frank.pet.name
答案 0 :(得分:0)
class Animal(object):
pass
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
##Dog has-a name
self.name = name
self.doglist = []
Dog.doglist.append("Rover")
这不起作用的原因是因为您尚未初始化Dog
对象。要纠正这个:
dog = Dog('Fido')
dog.doglist.append('Rover')
在__init__
方法中设置属性时,必须先将其初始化以访问该属性,否则它不存在。如果您希望所有Dog
个对象共享相同的列表,您可以:
class Dog:
dog_list = []
def __init__(self, name):
self.name = name
然后
>>> Dog.dog_list.append('Fido')
>>> Dog.dog_list
['Fido']
>>> dog = Dog('Rover')
>>> dog.dog_list
['Fido']
>>> dog.dog_list.append('Rover')
>>> dog.dog_list
['Fido', 'Rover']
>>> Dog.dog_list
['Fido', 'Rover']
在方法外部声明的属性将在该类的所有实例之间共享。