如何在python中调用类方法

时间:2015-02-09 21:08:13

标签: python

我有以下课程:

class SoftwarePackage:
    def __init__(self, name, description, order_of_installation, url):
        self.name = name
        self.description = description
        self.order_of_installation = order_of_installation
        self.url = "http://localhost:9090/api/software_package"

        def create():
            post_data = {"name": self.name, "description": self.description,
                         "order_of_installation": self.order_of_installation}
            post_data = json.dumps(post_data)
            req = urllib2.Request(url, post_data)

            req.add_header('Content-Type', 'application/json')
            return urllib2.urlopen(req, post_data)

当我尝试像这样调用“创建”方法时:

sp = SoftwarePackage(name="my-package-1", description="my-package-1-desc", order_of_installation=0, url="")
sp.create()

我收到此错误:

   sp.create()
AttributeError: SoftwarePackage instance has no attribute 'create'

调用此类方法的正确方法是什么?

1 个答案:

答案 0 :(得分:5)

您使create成为嵌套函数;你将它缩进到远,它是__init__方法的一部分。它目前是该方法中的局部变量,不可用。

Unindent 整个函数与def __init__(...):齐平,并添加self参数:

class SoftwarePackage:
    def __init__(self, name, description, order_of_installation, url):
        self.name = name
        self.description = description
        self.order_of_installation = order_of_installation
        self.url = "http://localhost:9090/api/software_package"

    def create(self):
        post_data = {"name": self.name, "description": self.description,
                     "order_of_installation": self.order_of_installation}
        post_data = json.dumps(post_data)
        req = urllib2.Request(self.url, post_data)

        req.add_header('Content-Type', 'application/json')
        return urllib2.urlopen(req, post_data)

url本地名称可能是实例上的url属性,因此我将其替换为self.url