我试着学习python2.7。当我运行此代码时:
class MyClass:
def PrintList1(*args):
for Count, Item in enumerate(args):
print("{0}. {1}".format(Count, Item))
def PrintList2(**kwargs):
for Name, Value in kwargs.items():
print("{0} likes {1}".format(Name, Value))
MyClass.PrintList1("Red", "Blue", "Green")
MyClass.PrintList2(George="Red", Sue="Blue",Zarah="Green")
我得到一个TypeError
:
MyClass.PrintList1("Red", "Blue", "Green")
TypeError: unbound method PrintList1() must be called with MyClass instance as first argument (got str instance instead)
>>>
为什么
我的班级是,一个班级
PrintList1是一个方法
方法需要在类的实例对象上调用
像这样:
要使其正常工作,还需要使方法采用
self
参数,如下所示:如果要将代码作为静态函数调用,则需要将staticmethod修饰符添加到类中,如下所示:
相关问题 更多 >
编程相关推荐