Kelvin Davis Kelvin Davis - 11 days ago 5
Python Question

Assigning a function return as another functions parameter

I've got this class and these functions below. Is there a way to assign the return value inside new_number to the parameter number in initial girl constructor?

class girl(person):
def __init__(self, number, interest):
self.number = number
self.interest = interest
super().__init__()
def new_number(self):
n = '0000000000'
while '9' in n[3:6] or n[3:6]=='000' or n[6]==n[7]==n[8]==n[9]:
n = str(random.randint(10**9, 10**10-1))
return n[:3] + '-' + n[3:6] + '-' + n[6:]

Answer

If you are always going to assign it to self.number then don't even accept it as a parameter. Simply call it and assign it:

class girl(person):
    def __init__(self, interest):
        self.number = self.new_number()
        self.interest = interest
        super().__init__()

    def new_number(self):
        n = '0000000000'
        while '9' in n[3:6] or n[3:6]=='000' or n[6]==n[7]==n[8]==n[9]:
            n = str(random.randint(10**9, 10**10-1))
        return n[:3] + '-' + n[3:6] + '-' + n[6:]

Note that new_number can be moved outside of the class as it has nothing to do with it, or it can be made static.

Comments