I'm trying to create a Company class and so far have written this code:
class Company:
def __init__(self, name, stocks_num, stock_price, comp_type):
self.name = name
self.stocks_num = stocks_num
self.stock_price = stock_price
self.comp_type = comp_type
if not self.valid(name,stocks_num, stock_price, comp_type):
raise ValueError("wrong Company Input")
def valid(self,name,stocks_num,stock_price,comp_type):
valid = True
check_list = [name, comp_type]
while check_list:
if ' ' in check_list[0] or not isinstance(check_list[0], str) or not check_list[0].replace(' ','').isalpha() or not check_list[0][0].isupper() \
or not len(check_list[0]) > 2:
valid = False
check_list.pop(0)
if not isinstance(stocks_num, int) or not stocks_num > 0:
valid = False
if not isinstance(stock_price, int) and not isinstance(stock_price, float) or not stock_price > 0:
valid = False
return valid
and as you can see I have this kind of validation process that works well for me, the problem is I want to create functions that change the instances' name, stock num, etc' and I want these function inputs to have the same validation process the original instance input had.
for example:
def set_name(self, name):
# change company name
*checks if only the name is valid*
self.name = valid_new_name
Is there any way to do it without duplicating the same code from the __init__
? or having to input all the valid()
arguments instead of just the one I want?