Yusuf Ning Yusuf Ning - 3 months ago 9
Python Question

class and methods in python. introduction in oop

class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name

def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname)

# Use the class to introduce Mark and Steve
mark = Person("Mark")
steve = Person("Steve")

print(mark.introduction())
print(steve.introduction())


its suppose to produce
"Hi, my name is Mark." or "Hi, my name is Steve."

but instead it produces
"Hi, my name is undefined."

Answer

It should be printing the object's representation in memory (something along the lines of Hi, my name is <__main__.Person object at 0x005CEA10>).

The reason is that the first argument of a method is expected to be the object that the method is called upon.

Just like you have def __init__(self, name): you should have def introduction(self, myname):.

Then you will encounter another problem, as introduction now expects an argument myname which you don't provide it. You don't actually need it since you now have access to self.myname.

class Person:
    def __init__(self, name):
        """Make a new person with the given name."""
        self.myname = name

    def introduction(self):
        """Returns an introduction for this person."""
        return "Hi, my name is {}.".format(self.myname)


# Use the class to introduce Mark and Steve
mark = Person("Mark")
steve = Person("Steve")

print(mark.introduction())
print(steve.introduction())

Will output

Hi, my name is Mark.
Hi, my name is Steve.
Comments