Python 实例方法与静态方法

标签 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():
            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)
>>> 

为什么?

最佳答案

MyClass 是一个类。

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))

如果您想将代码作为静态函数调用,则需要将 staticmethod 装饰器添加到您的类中,如下所示:

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")

关于Python 实例方法与静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020891/

相关文章:

delphi - 无法编译受约束的泛型方法

c++ - 如何在不知道类型的情况下声明模板指针?

python - IMDBPy 安装 mysqlclient 失败 - Python 2.7 Windows

python - django 迁移 "No migrations to apply."

python - 如何在 python 中更改图像的 HSV 值?

python - 如何使用 os.walk() python 计算目录的大小?

python - Python 的 SignalR 替代方案

c# - 在静态类上查找泛型方法

python - 重命名 Excel 选项卡

python - 创建类的实例时无法传递参数