Search code examples
pythonattributesattributeerror

Error in Python regarding Attributes missing (formatted the right way hopefully)


I'm trying to define a method called getX on my object as it's 2nd of 3 parts to a problem (It's part of a longer problem as I'm doing a stand-alone online course so no help)

Here's what my class looks like

class V2:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'V2[%s,%s]' % (self.a, self.b)

    def FindThis(self, a, b):
        self.getX = self.a
        self.getY = self.b

I then type

v = V2(1,2)
v.getX()

When I create an instance of this class and call .getX() I get the following error

Traceback (most recent call last): File "<pyshell#2>", line 1, in <module>
v.getX() AttributeError: V2 instance has no attribute 'getX'

note: The goal of this program is to define basic part of the class with an init and str methods so that if you do

print V2(1.1,2.2)

it prints

V2[1.1,2.2]

and then write two accessor methods (getX and getY) that return the x and y components of the vector

My struggle-point is not knowing how to use/where to put getX and getY in my program to deliver what the problem is asking me to do

Note: I've posted the question before but in a terrible format and didn't make clear what I needed help with. Hope this was clearer


Solution

  • You need to make a few adjustments to your code:

    class V2:
        def __init__(self, a, b):
            self.x = a
            self.y = b
    
        def __str__(self):
            return 'V2[%s,%s]' % (self.x, self.y)
    
        def getX(self):
            return self.x
    
        def getY(self):
            return self.y
    
    v = V2(1,2)
    >>> print v.getX()
    1
    
    >>> print v
    V2[1,2]