-5

i am having issues with my code. i have a python class and functions it. i want to be able to call the function inside it to another function, below is my code

import random

class now:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def num1(self):
        print('One')

    def num2(self):
        print('Two')

    def num3(self):
        print('Three')

    def all(self):
        num = [self.num1, self.num2, self.num3]
        random.choice(num)()

    def start(self):
        print('my name is: ', self.name)
        print('i choose:', self.all() )


my_take = now('king')

my_take.start()

my problem now is that when i run the code, on the i choose, self.all() is given me none

kuro
  • 3,214
  • 3
  • 15
  • 31
  • Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Mechanic Pig Jun 03 '22 at 07:45

2 Answers2

2

Your all method has no return statement in it, so it implicitly returns None.

ndc85430
  • 1,395
  • 3
  • 11
  • 17
1

You have to return the Strings, not print them. Try it like this:

import random

class now: 
    def __init__(self, name):
        self.name = name
        
    def get_name(self):
        return self.name
    
    def num1(self):
        return 'One'
    
    def num2(self):
        return 'Two'
    
    def num3(self):
        return 'Three'
    
    def all(self):
        num = [self.num1, self.num2, self.num3]
        return random.choice(num)()
    
    def start(self):
        print('my name is: ', self.name)
        print('i choose:', self.all() )

You are using a lot of Methods to accomplish a very simple tast. Why dont try it like this:

import random

class now: 
    def __init__(self, name):
        self.name = name
        
    def get_name(self):
        return self.name
    
    def start(self):
        print('my name is: ', self.name)
        print('i choose:', random.choice(["One", "Two", "Three"]) )
alanturing
  • 214
  • 1
  • 8
  • Even at that, it still shows None – chibuike ogodo Jun 03 '22 at 07:13
  • If I run exactly this code I don't get None but a number. @chibuike ogodo. It outputs following: ```my name is: king i choose: One``` – alanturing Jun 03 '22 at 07:18
  • on you second answer, that's not what i want. thou i just used this simple terms on it. i wanted to create different functions with different behavior and have them randomly selected. but then i needed to use the simple term to illustrate. But i have been able to do it. thank for your help – chibuike ogodo Jun 03 '22 at 07:20
  • you are getting None because nothing is actually running, it is only interpreting the code. To run it, initialize the class with a name then call .start() – Noah Jun 03 '22 at 07:21