0

I have a function which returns an object of class Person, defined as:

class Person:
    def __init__(self):
        self.id=None
        self.age=0
        self.name=None

    def setValues(self,id,age,name):
        self.id=id_
        self.age=age_
        self.name=name_

And here is a function which returns such an object:

def getTeacher():
    pr = Person()
    pr.setValues(11,"John",30)
    return pr

Now, I want to assign the object returned by this function to another object in main:

teacher=getTeacher()

But it turns out teacher is a null object. Please help

4
  • 1
    getTeacher() requires two parameters. You call it with no parameters. That must have caused a runtime error. If you did not have an error, then the code that you show is not the code that you executed. Please kindly update your question. Commented Jun 26, 2020 at 8:12
  • Is get teacher existing inside some class? or is it meant to be just a function. getTeacher takes two inputs (ore one if its a class method), yet in your code you pass none. so this will give a type error. Please make a minimum runable code example Commented Jun 26, 2020 at 8:15
  • Okay I have changed. Still the issue remains tho Commented Jun 26, 2020 at 8:19
  • 1
    I tested the current version of the posted code and was unable to reproduce the reported result. It blew up in setValues because ``id_` was not defined. Commented Jun 26, 2020 at 8:34

1 Answer 1

0

You should remove the parameters in getTeacher function, since the function is not inside the class Person, and id is not used in the function. You could get the teacher after this correction.

class Person:
    def __init__(self):
        self.id=None
        self.age=0
        self.name=None

    def setValues(self,id_,name_,age_):
        self.id=id_
        self.age=age_
        self.name=name_

def getTeacher():
    pr = Person()
    pr.setValues(11,"John",30)
    return pr

teacher=getTeacher()
print(teacher.id)
Sign up to request clarification or add additional context in comments.

2 Comments

Remove self too and move getTeacher() function out of the class.
hmm. It works just as expected on my end. With teacher=getTeacher(), you get the Person object, please try print(teacher.age) at the end to see whether you could access the attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.