0

I have defined a simple class.

class Person:

    age = 0
    name = ''


    def __init__(self,personAge,personName):
        self.age = personAge
        self.name= personName

        def __str__(self):
            return self.name


d = Person(24,'ram')
print(d)

so o/p is coming like this <__main__.Person object at 0x0000020256652CF8> .But i want o/p like this ram. How can i get this?

please be correcting me.Thnaks in adavance

1
  • Improve your identation Commented May 7, 2018 at 5:43

3 Answers 3

4

your indentation is wrong. Your overrided str inside init (constructor). Also you don't have to specify class variables if you are getting/initialising the variables through constrcutor. try below, `

class Person:

    def __init__(self,personAge,personName):
        self.age = personAge
        self.name= personName

    def __str__(self):
        return self.name


d = Person(24,'ram')
print(d)

`

Sign up to request clarification or add additional context in comments.

1 Comment

please accept it as answer if it had solved your problem.
1

You are printing the class object, not return value of the method (see last line here). Possible indentation issue for __str__() method fixed, too.

class Person:

    age = 0
    name = ''


    def __init__(self,personAge,personName):
        self.age = personAge
        self.name= personName

    def __str__(self):
        return self.name


d = Person(24,'ram')
print(d.__str__())

See also PEP 8 for naming conventions.

Comments

1
    class Person:
         age = 0
         name = '' 

        def __init__(self, personAge, personName): 
              self.age = personAge
              self.name= personName 

        def __str__(self): 
               return self.name 

d = Person(24,'ram') 
print(d)

__str__ should be out of __init__ scope

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.