Home > Back-end >  How do i call a function within a class in python
How do i call a function within a class in python

Time:06-03

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

CodePudding user response:

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

CodePudding user response:

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"]) )
  • Related