为什么我的实例计数器在这个Python代码中显示为0?

为什么我的实例计数器在这个Python代码中显示为0?,python,debugging,class,Python,Debugging,Class,我编写了一个简单的代码来演示和理解类——但是当我运行这个程序时,我的列表显示它们是空的,包含“None”值,而不是用户输入的字符串作为名称 #Static methods do not require the object to be initiated. Can be remotely accessed from outside the function . #Counting critters and remote access. class Orc (object): tot

我编写了一个简单的代码来演示和理解类——但是当我运行这个程序时,我的列表显示它们是空的,包含“None”值,而不是用户输入的字符串作为名称

#Static methods do not require the object to be initiated. Can be remotely accessed from outside the function .

#Counting critters and remote access.

class Orc (object):

    total = 0       

    def get_score (self):
        print "The number of orcs the orc factory has made is",Orc.total   

    def __init__ (self):
        Orc.total += 1
        name =  raw_input ("I am a critter by the name of:\n")


#Creating 10 Orcs 


list = []

for i in range (4):    list[i] = list.append(Orc.get_score(Orc()))  

print "You have created 4 Orcs!" print "The name of your first orc is",list[0] print "The name of your fourth orc is", list[3]

list.append
返回一个
None
值,因此将其结果分配给任何对象基本上都没有意义。您可以调用
append
,以获得副作用,即在列表末尾添加一个值。像这样:

for i in range (4):    
    list.append(Orc.get_score(Orc()))

我也不认为
Orc.get_score(Orc())
是您想要的:它还返回
None
而不是score,方法调用在技术上是正确的,但不太可能是您真正想要的

为什么你的清单上会有什么

你可以:

list.append(Orc.get_score(Orc())
这相当于:

item_to_add = Orc.get_score(Orc())
list.append(item_to_add)
您的方法
Orc.get\u score
没有返回语句,因此它返回
None
。因此,要添加的项目将为None,并且不会将None追加到列表中


作为旁注:python不是java。不要仅仅为了使用类而使用类。当您想要遵循OO Pradigma,即向对象发送消息时,请使用类。

要在Python中定义类方法,请使用
classethod
decorator并调用第一个参数
cls

class Orc(object):

    total = 0       

    @classmethod # this will make the method a class method
    def get_score (cls): # convention is then to call the 1st param 'cls'
        print "The number of orcs the orc factory has made is", cls.total   

    def __init__ (self):
        Orc.total += 1
        # use self is you want' to register a name
        # however putting a raw_input in an __init__ is NOT recommanded
        # you should pass name as a parameter 
        # and call the raw_input in the for loop
        self.name =  raw_input ("I am a critter by the name of:\n")

orcs = [] # don't call your lists 'list' because `list` is standard Python function

for i in range(4): # put this on two lines for clarity or use a comprehension list
   orcs.append(Orc())  

print "You have created 4 Orcs!" 
print "The name of your first orc is", orcs[0].name # if you don't use `name`, you will see the reference of the object

print "The name of your fourth orc is", orcs[3].name
更干净的版本(你应该瞄准的目标):

现在是更具Python风格的版本(在使用Python之后,您应该能够做到这一点):


您的代码中有一些错误。首先是你使用列表的方式。其次,在对象上调用方法的方式上。这些错误的组合解释了为什么在末尾有一个
None
列表

列表名 不要给列表命名
list
。它已经是list类的名称,也就是说,在Python中,您可以使用完全相同的效果来执行
my_list=[]
my_list=list()

你想把你的列表称为有意义的东西,比如
orc\u list

列表插入
orc_list.append
执行它所说的操作:将一个元素附加到给定的列表中。但是,它不会返回任何内容。因此,您的代码所做的是

  • 拿空名单
  • i
    设置为0
  • 在列表末尾插入传递给
    的内容追加
  • 在索引
    i
    处插入
    None
    ,从而覆盖您在3中所做的操作
  • 递增
    i
  • 回到3
  • 您只需使用
    orc\u list.append(…)

    方法调用 我想你被
    self
    的论点弄糊涂了。在类中,Python将自动将您正在处理的实例作为
    self
    参数传递。你不需要提供那个论点

    你想写作吗

    Orc().get_score()
    
    这将创建一个
    Orc
    对象,然后对其调用
    get\u score
    。Python将您创建的
    Orc
    实例“注入”到
    get_score

    方法返回 我们现在要做的是

    orc_list.append(Orc().get_score())
    
    这相当于

    score = Orc().get_score()
    orc_list.append(score)
    
    问题是
    get\u score
    中没有
    return
    语句。这意味着调用该方法时python将返回
    None
    。这意味着您正在将
    None
    添加到列表中

    你想要什么

    def get_score(self):
        print "The number of orcs the orc factory has made is", Orc.total
        return Orc.total
    
    静态行为 如果您确实想要一个方法不绑定到
    Orc
    类的实例,可以使用a或a

    在您的情况下,不需要对类对象执行任何操作,因此您可以选择使用静态方法

    你要申报吗

    @staticmethod
    def get_score():
        print "The number of orcs the orc factory has made is", Orc.total
    

    然后,您可以使用
    Orc.get_score()

    调用该方法。请不要在python中为列表命名“list”。另外,请阅读python中的类教程。你需要弄清楚你的语法。-1,你至少可以阅读列表对象的文档
    append
    已经在列表中添加了一些内容,不需要设置。我认为它不值得-1,很明显,这是一个不知道自己在做什么的人,独自一人来解决它,需要帮助。当你不知道问题所在时,很难提出正确的问题。有趣的是,现在一个不到4000名的代表用户可能会有多么咄咄逼人。-1许多问题--#1其中一个可能是发布的代码从未运行过。第四个orc s/b orc的名称[3]。名称冷静martineau:首先,我写了一个anwser来解决他的问题,然后,我对它进行了改进,以确保它是空的。你知道我可能不是用笔记本电脑上的Python编译器写这篇文章的吗?我真的很感激这个详细的答案。如果可以的话,我会投票两次。OP得到
    None
    的原因是
    get\u score()
    没有
    返回值。@martineau-Oops!我不再使用
    append
    查看错误,因为这是一个非常常见的错误。我会修改最后一句。答案很好,但它没有提到使用
    Orc.get_score(Orc())
    (或者
    Orc().get_score()
    )还有一个不良的副作用,那就是导致
    Orc.total
    class属性递增,从而导致计数延迟。@Martineau:与其批评其他人,写一个符合你标准的怎么样?@rodrigue:+1逐步解释。@martineau我不认为这是一个不良的副作用。我知道这正是@Louis93试图做的:计算创建的实例数。@Rodrigue:也许吧,但我怀疑副作用是不必要的,因为创建一个
    Orc
    实例只是为了调用它的方法,所以即使它立即被丢弃,它也会被计数。
    Orc().get_score()
    
    orc_list.append(Orc().get_score())
    
    score = Orc().get_score()
    orc_list.append(score)
    
    def get_score(self):
        print "The number of orcs the orc factory has made is", Orc.total
        return Orc.total
    
    @staticmethod
    def get_score():
        print "The number of orcs the orc factory has made is", Orc.total