我正在玩下面的课程来练习我的Python技能:
class Scene(object):
def __init__(self, settings, actors):
self.settings = int(settings)
self.actors = actors
actors = []
new_setting = settings = settings + 1
class Actor(object):
def __init__(self, name, wage):
self.name = name
self.wage = wage
def addActor(self):
self.name = name
self.wage = wage
self.actors.append(name)
Scene1 = Scene(3, ["Tom Hanks", "Meg Ryan"])
Scene1.addActor(Actor("Paul Giamatti"))
我希望能够为变量'Actor'添加多个功能。 例如,我想给汤姆汉克斯一个年龄和工资等。
我尝试通过在函数addActor中定义几个子变量来实现这一点,但这给了我错误。我是否必须创建一个名为Actors的子类并以这种方式执行?
谢谢!
答案 0 :(得分:2)
最好的方法是为Actor
定义另一个类,请参阅下面的示例
class Actor(object):
def __init__(self, name, age, wage):
self.name = name
self.age = age
self.wage = wage
class Scene(object):
def __init__(self, settings):
self.settings = settings
self.actors = []
def addActor(self, name, age, wage):
actor = Actor(name, age, wage)
self.actors.append(actor)
def listActor(self):
for actor in self.actors:
print "Actor name:", actor.name
print "Actor age:", actor.age
print "Actor wage:", actor.wage
# Usage
scene = Scene({"light":True, 'time':'day'}) # settings can be a dictionary depends on your use case
scene.listActor()
print scene.settings