0

I have the following class:

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)

When I try to call the "create" method like this:

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

I get this error:

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

What is the proper way to call this class method?

0

1 Answer 1

4

You made create a nested function; you indented it to far and it is part of the __init__ method. It is currently a local variable in that method and not usable.

Unindent the whole function to be level with def __init__(...):, and add a self argument:

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)

The url local name is probably meant to be the url attribute on the instance, so I replaced that with self.url.

Sign up to request clarification or add additional context in comments.

1 Comment

The url member data needs to be referenced using self

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.