我有以下课程:
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'
调用此类方法的正确方法是什么?
答案 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
。