0
 class Box:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def get_length(self):
        return self.length
    def get_width(self):
        return self.width    
    def double(self):
        self.length = 2*(self.length)
        self.width = 2*(self.width)
        return self.length
        return self.width

I have this issue below.

self.assertEqual(b1.double().get_length(),32)  
AttributeError: 'int' object has no attribute 'get_length'

These length and width attributes should be private and accessible only via getters. How can I fix this?

MikaelF
  • 3,518
  • 4
  • 20
  • 33
Emily
  • 1
  • 1
  • your `double` method returns an int which you you then trying to use to call `get_length` hence the problem – Kenan Mar 08 '20 at 04:40
  • the error in your code has nothing to do with private and public. b1.double() is an integer (from your code). int have not 'get_length', What are you trying to do? – mm_ Mar 08 '20 at 04:41
  • Your method `double()` is pretty confusing. It returns twice ( only the first return does anything) and returns and integer. This is why calling `.double().get_length()` is an error. You are trying to call `get_length()` on the return value of `.double()`, which is an int. – Mark Mar 08 '20 at 04:41
  • You receive length by calling `double()`. PS: Two unconditional `return`s won't return two, but just the first one. – Austin Mar 08 '20 at 04:41
  • Python doesn't *have* private member variables at all. The nearest thing there is (`self.__length` / `self.__width` -- note the underscores being doubled) is merely obfuscation (whereas `self._length` and `self._width`, with a single leading underscore each, is a *convention* used to *politely request* that other code stay out of your variables). – Charles Duffy Mar 08 '20 at 04:50

2 Answers2

0

Method double() returns an integer number (self.length). You attempt to call the method get_length() of that number, and it does not have it. Suggested solution: replace return self.length with return self.

DYZ
  • 55,249
  • 10
  • 64
  • 93
0

Your double() method has two returns statements, the 2nd of which will never execute so that's issue number one.

Second issue is, it seems, you want to return a new Box object with double the values, however what you're doing is doubling the values of the current one and then returning the length (an int).

This is probably what you're trying to do:

def double(self):
    return Box(self.__length * 2, self.__width * 2)

That way the Box(1, 2).double().get_length() will give you what you expect - a 2.


As an aside, it seems that you are new to python. Unlike other languages, in python there's generally no need to have "private" attributes (they can still be accessed if you really want). Generally just using self.length and self.width is enough. If you ever want to add some logic on access, use a @property decorator.

More information.

Anonymous
  • 11,740
  • 3
  • 40
  • 50