-5
class Person:
  def __init__(self, name):
    self.name = name

  def greet(name, other_name):
    return "Hi {0}, my name is {1}".format(other_name, name)

Why doesn't this work? I am trying to access my name in the class and say hi my name is [myname] [yourname]

martineau
  • 119,623
  • 25
  • 170
  • 301
Noah
  • 120
  • 1
  • 8

4 Answers4

2

Your actual problem is that you are defining your instance method greet as:

def greet(name, other_name):

Instance methods in Python take the instance as first argument in your method definitions. What you are doing here now, is calling that instance name. However, in your class's __init__, you are using self to refer to your instance object. This is where your main problem is coming up.

So, when you actually try to call your method, you are most likely getting something like this:

Hi bob, my name is <__main__.Person object at 0x1018ff2b0>

So, you are actually printing out your instance object of your Person class. Again, you named this name. It's like printing out self.

There are two things you need to correct here. The first, you need to properly define your instance greet method keeping your instance object name consistent.

def greet(self, other_name):

Then, you need to refer to your instance attributes referring to your instance and accessing the attributes from that object:

So, you want to access name in your greet method, it has to be as self.name.

So:

"Hi {0}, my name is {1}".format(other_name, self.name)

To have a better grasp on all this, you should read more on how classes work in Python. Here is the tutorial section on it:

https://docs.python.org/3/tutorial/classes.html

idjaw
  • 25,487
  • 7
  • 64
  • 83
0

use self.name instead of name:

def greet(other_name):
    return "Hi {0}, my name is {1}".format(other_name, self.name)
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

There are two possibilities:

1) You want greet() method to be an instance method, then you lack the self parameter:

def greet(self, other_name):
    return "Hi {0}, my name is {1}".format(other_name, self.name),

Then you can invoke it like this:

adam = Person("Adam")
adam.greet("John")

2) You want it to be a static method:

@staticmethod
def greet(name, other_name):
    return "Hi {0}, my name is {1}".format(other_name, name)

Then you can invoke it like this:

Person.greet("Adam", "John")
Jakub Jankowski
  • 731
  • 2
  • 9
  • 20
0

You need to pass self to the method

Why do you need explicitly have the "self" argument into a Python method?

so

 def greet(self, name, other_name):
    return "Hi {0}, my name is {1}".format(other_name, name)
Community
  • 1
  • 1
somesingsomsing
  • 3,182
  • 4
  • 29
  • 46
  • 2
    This is strange. Why would this be the accepted solution, when `self.name` is defined in the `init` and then passing it as an argument to the `greet` method. This doesn't make much sense. – idjaw Oct 10 '16 at 21:35