Python实例方法与静态方法
我尝试学习Python 2.7。当我运行此代码时:Python实例方法与静态方法,python,python-2.7,generics,Python,Python 2.7,Generics,我尝试学习Python 2.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(): pr
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")
我得到一个类型错误
:
MyClass.PrintList1("Red", "Blue", "Green")
TypeError: unbound method PrintList1() must be called with MyClass instance as first argument (got str instance instead)
>>>
为什么?我的班级是一个班级
PrintList1是一种方法
需要对类的实例化对象调用方法
像这样:
myObject = MyClass()
myObject.PrintList1("Red", "Blue", "Green")
myObject.PrintList2(George="Red", Sue="Blue", Zarah="Green")
要使其正常工作,还需要使方法采用self
参数,如下所示:
class MyClass:
def PrintList1(self, *args):
for Count, Item in enumerate(args):
print("{0}. {1}".format(Count, Item))
def PrintList2(self, **kwargs):
for Name, Value in kwargs.items():
print("{0} likes {1}".format(Name, Value))
class MyClass:
@staticmethod
def PrintList1(*args):
for Count, Item in enumerate(args):
print("{0}. {1}".format(Count, Item))
@staticmethod
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")
如果要将代码作为静态函数调用,则需要将staticmethod装饰器添加到类中,如下所示:
class MyClass:
def PrintList1(self, *args):
for Count, Item in enumerate(args):
print("{0}. {1}".format(Count, Item))
def PrintList2(self, **kwargs):
for Name, Value in kwargs.items():
print("{0} likes {1}".format(Name, Value))
class MyClass:
@staticmethod
def PrintList1(*args):
for Count, Item in enumerate(args):
print("{0}. {1}".format(Count, Item))
@staticmethod
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")
为什么要尝试在类上调用实例方法,而您的
self
参数在哪里?坦率地说,将这些方法放在一个类中似乎毫无意义。