Python类脚本运行错误?

2024-04-20 07:42:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python2.7.9创建一个类,但它总是出错

这是我的剧本:

class Hero():
    def __init__(self, name):

        self.health=50
    def eat(self, food):
        if(food=='apple'):
            self.health+=10
self.name=Jeff
Jeff=Hero('Jeff')

def introduce(self, name):
    print Jeff.name

def checkAtt():
    print Jeff.health

introduce()

它一直在说name 'Jeff' is not defined


Tags: nameselfappleiffoodinitdefclass
1条回答
网友
1楼 · 发布于 2024-04-20 07:42:50

你的代码有很多问题。第一个导致特定错误的原因是您试图分配:

self.name = Jeff

在定义selfJeff之前self通常只在实例方法内部使用(比如Hero.eat),其中它是第一个参数的名称


其次,您的Hero.__init__实际上并没有将name参数赋给name属性;它应该看起来像:

class Hero(object): # Note inheritance from 'object' for new-style class

    def __init__(self, name):
        self.name = name # Note assignment of instance attribute
        self.health = 50

    ...

jeff = Hero("Jeff")将调用Hero.__init__,创建新的Hero实例,将其name属性设置为"Jeff"(将health属性设置为50),并将该实例分配给名称jeff


第三,您有两个独立函数(introducecheckAtt),它们可能也是实例方法:

def Hero(object):

    ...

    def introduce(self):
        print self.name

...

jeff = Hero("Jeff")
jeff.introduce() # equivalent to 'Hero.introduce(jeff)'

或者,如果仍然是独立的函数,就使用一个参数Hero实例来操作(按照惯例,它不应该被称为self)-编写一个只在名称Jeff可用的范围内运行的函数没有多大意义

class Hero(object):

    ...

def introduce(hero):
    print hero.name

jeff = Hero("Jeff")
introduce(jeff)

注意这两种不同情况下的缩进在Python中非常重要。另外,请注意调用introduce的不同方式,这取决于它是实例方法还是函数


我建议你读the tutorial on classesthe style guide

相关问题 更多 >