Why is "None" coming up?

Asked 2 years ago, Updated 2 years ago, 21 views

class Friend:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
    def get_name(self, input_name):
        self.name = input_name
    def get_phone (self, input_phone):
        self.phone = input_phone

name = input ('Enter name:')
phone = input ('Enter phone number:')

f = Friend(name,phone)

print(f.get_name(name))
print(f.get_phone(phone))

When you run

None
None

It pops up like this. What's the problem and what's the solution?

python

2022-09-29 01:00

2 Answers

Because there is no return value.
Methods with "get_" are commonly used as methods with "set_".

def get_name(self):
    return self.name

def set_name(self, name):
    self.name = name


2022-09-29 01:00

This is because the function has no return value. Try to modify it in the following way.

class Friend:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
    def get_name(self, input_name):
        self.name = input_name
        return self.name
    def get_phone (self, input_phone):
        self.phone = input_phone
        return self.phone

name = input ('Enter name:')
phone = input ('Enter phone number:')

f = Friend(name,phone)

print(f.get_name(name))
print(f.get_phone(phone))

Or

class Friend:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
    def get_name(self, input_name):
        print(input_name)
    def get_phone (self, input_phone):
        print(input_phone)

name = input ('Enter name:')
phone = input ('Enter phone number:')

f = Friend(name,phone)

f.get_name(name)
f.get_phone(phone)


2022-09-29 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.