2
class HouseLocation():

    def __init__(self,street_name,x,y):
        self.street_name=street_name
        self.x=x
        self.y=y

      def print_address():
          print '{}: {},{}'.format(street_name,x,y)

I assume the code is very simple and explains itself I would assume now my problem is when I try to run it

k=HouseLocation('lol lo', 3,7)

k.print_address()

I get the following error message

Traceback (most recent call last):

File "", line 1, in

k.print_address()

TypeError: print_address() takes no arguments (1 given)

Can someone please explain what I am doing wrong?

Enigma
  • 129
  • 1
  • 7
  • 1
    Add `self` as parameter to the method – fafl Jan 11 '17 at 23:02
  • 1
    Methods are passed the object that owns them as the first parameter. By convention, we call this `self` in Python (but `def foobar_method(omg_its_me)` is syntactically valid). Note also that `street_name`, `x`, and `y` aren't defined inside `HouseLocation.print_address`. Since methods get their owners as the first argument, you get to use their attributes, but you have to refer to them as such! (`self.street_name`, `self.x`, `self.y`) – Adam Smith Jan 11 '17 at 23:06

5 Answers5

3

Remember that methods take the self argument implicitly. Change the method code to:

  def print_address(self):
      print '{}: {},{}'.format(self.street_name,self.x,self.y)
lukeg
  • 4,189
  • 3
  • 19
  • 40
1

self is the missing parameter, which is passed as the first argument of all class methods.

def print_address(self):
    print '{}: {},{}'.format(self.street_name,self.x,self.y)
esmit
  • 1,748
  • 14
  • 27
1

You should pass self to print_address()

def print_address(self):
    print '{}: {},{}'.format(self.street_name, self.x, self.y)
ettanany
  • 19,038
  • 9
  • 47
  • 63
1

The first parameter of a function should be the self parameter. That is your instance of the class and allows you to get/set properties accordingly.

class HouseLocation():

    def __init__(self,street_name,x,y):
        self.street_name=street_name
        self.x=x
        self.y=y

    def print_address(self):
        print '{}: {},{}'.format(self.street_name,self.x,self.y)
dana
  • 17,267
  • 6
  • 64
  • 88
1

self is the missing parameter here. The function needs to have at least one argument where one of those is self whenever in a class:

def print_address(self):
      print '{}: {},{}'.format(self.street_name,self.x,self.y)

Then to avoid NameError, add self. in front of the variables.

Anthony Pham
  • 3,096
  • 5
  • 29
  • 38