0

I main java and just started on python, and I ran into this error when I was trying to create a class. Can anyone tell me what is wrong?

import rectangle

a = rectangle(4, 5)

print(a.getArea())

this is what is in the rectangle class:

class rectangle:
    l = 0
    w = 0

    def __init__(self, l, w):
        self.l = l
        self.w = w

    def getArea(self):
        return self.l * self.w

    def getLength(self):
        return self.l

    def getWidth(self):
        return self.w

    def __str__(self):
        return "this is a", self.l, "by", self.w, "rectangle with an area of", self.getArea()
4
  • Please, don't post images of code, error, etc. Copy/paste as properly formatted text block here. Commented Nov 4, 2021 at 18:17
  • how do u insert a code block? Commented Nov 4, 2021 at 18:19
  • @ir6 See: stackoverflow.com/editing-help Commented Nov 4, 2021 at 18:20
  • 2
    your calling rectangle as a class when it's a module, if you do have the rectangle class inside of the rectangle object, you would need to do rectangle.rectangle(4,5) Commented Nov 4, 2021 at 18:21

2 Answers 2

2

I don't know what you have implemented in the rectangle module but I suspect that what you're actually looking for is this:

from rectangle import rectangle
a = rectangle(4, 5)
print(a.getArea())

If not, give us an indication of what's in rectangle.py

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

3 Comments

nice it work! ty!
Thought so :) Just so you know, when you do import recrangle, you add the rectangle MODULE (file) to the namespace. If you want to call the class using that, you would have had to do a = rectangle.rectangle(4, 5). In that case, the first rectangle is the name of the module, while the second rectangle is the name of the class. On the other hand, from rectangle import rectangle tells the interpreter that from the module rectangle import class rectangle and add that to the namespace. Hope that helps you understand this better :) Don't forget to thumbs up and accept the answer. Cheers!
Also, piece of advice in the future, it's usually a good practice to name the modules with lower case and the classes with upper case. Meaning you would have class Rectangle: and you'd import it as from rectangle import Rectangle. This helps distinguish if rectangle that you import into the namespace is a class (uppercase) or a function (lowercase). Hope this helps. Cheers!
0

your gonna need to specify what module the function is from so either import all the functions so change import rectangle to from rectangle import *

or switch the rectangle(4,5) to rectangle.rectangle(4,5)

1 Comment

star import is considered bad style

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.