Lou*_*s93 0 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):
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]
Run Code Online (Sandbox Code Playgroud)
您的代码中存在一些错误.首先是你使用列表的方式.其次,在对象上调用方法的方式.错误的组合解释了为什么你最后有一个列表None.
list = []
Run Code Online (Sandbox Code Playgroud)
不要列出名单list.它已经是,列表类的名称,即在Python中你可以做my_list = []或my_list = list()具有完全相同的效果.
你想把你的列表称为有意义的东西,比如 orc_list
for i in range (4):
orc_list[i] = orc_list.append(...)
Run Code Online (Sandbox Code Playgroud)
orc_list.append做它说的:它将一个元素附加到给定的列表.但是,它并没有返回任何东西.那么你的代码正在做什么
i0append列表末尾None索引i,从而覆盖你在3中所做的事情.i你想简单地使用 orc_list.append(...)
Orc.get_score(Orc())
Run Code Online (Sandbox Code Playgroud)
我想你会被这个self论点搞糊涂了.在类中,Python将自动传递您正在处理的实例作为self参数.您不需要提供该参数.
你想写
Orc().get_score()
Run Code Online (Sandbox Code Playgroud)
这会创建一个Orc对象,然后调用get_score它.Python' 为您注入' Orc您创建的实例get_score.
我们现在已经到了
orc_list.append(Orc().get_score())
Run Code Online (Sandbox Code Playgroud)
这相当于
score = Orc().get_score()
orc_list.append(score)
Run Code Online (Sandbox Code Playgroud)
问题是没有return声明get_score.这意味着None当您调用该方法时,python将返回.这意味着您要附加None到列表中.
你想拥有
def get_score(self):
print "The number of orcs the orc factory has made is", Orc.total
return Orc.total
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一个没有绑定到Orc类实例的方法,你可以使用类方法或静态方法.
在您的情况下,您不需要对类对象执行任何操作,因此您可以选择使用静态方法.
你会宣布
@staticmethod
def get_score():
print "The number of orcs the orc factory has made is", Orc.total
Run Code Online (Sandbox Code Playgroud)
然后,您将使用该方法调用 Orc.get_score()
要在Python中定义类方法,请使用classethoddecorator并调用第一个参数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
Run Code Online (Sandbox Code Playgroud)
更清洁的版本(你应该瞄准的东西):
class Orc(object):
total = 0
@classmethod #
def get_instances_count(cls):
"""
Return the number or orcs that have been instanciated
"""
# ^ Put some documentation below your method
# these are called "docstring" and are detected by Python
# you should return values in method rather than print
# there are rare cases when you do want print, but when you'll
# encounter them, you won't need me to correct your code anymore
return cls.total
def __init__ (self, name):
Orc.total += 1
self.name = name # we get the name as a parameter
l = []
for i in range(4): # put this on two lines for clarity or use a comprehension list
orc = Orc(raw_input("Enter a name:\n"))
l.append(orc)
print "You have created %s Orcs!" % Orc.get_instances_count()
print "The name of your first orc is", l[0].name #
print "The name of your fourth orc is", l[3].name
Run Code Online (Sandbox Code Playgroud)
现在更多的Pythonic版本(一旦用于Python,你应该可以做的事情):
class Orc(object):
total = 0
# you don't need accessors in Python: most things are public anyway
# and you got property
def __init__ (self, name):
Orc.total += 1
self.name = name # we get the name as a parameter
def __str__(self):
# this will be call when printing an orc
return self.name
# list comprehension are quick and clean ways to create lists
# give a real name to your list
orcs = [Orc(raw_input("Enter a name:\n")) for i in range(4)]
# using parenthesis for `print` is a good habit to take with then incoming Python 3
print("You have created %s Orcs!" % Orc.total)
for i, orc in enumerate(orcs):
print("Orc #%s is %s" % (i, orc))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |