下面的代码有效,但是很笨重,我希望hippo实例采用五个值,而不是在init方法中前两个的'description'方法中交换最后两个,以及类变量'' is_alive”。
class Animal(object):
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def description(self, location, diet):
print location
print diet
hippo = Animal("Jimmy",3)
#hippo = Animal.description(hippo, "zoo", "plants") #errors
print hippo.name
print hippo.age
print hippo.is_alive
hippo = Animal.description(hippo, "zoo", "plants") #instance takes on
#new values -- don't want that; want to append to init values
print hippo
>>>
Jimmy
3
True
zoo
plants
答案 0 :(得分:2)
hippo
是Animal
的实例,您应该调用以下函数:
hippo.description("zoo", "plants")
这里我举一个例子:
class Animal:
def desc(self):
print("desc is invoked...")
@staticmethod
def description():
print("description is invoked..")
hippo = Animal()
hippo.desc()
Animal.description()