递归调用私有方法
Calling Private Methods Recursively
我正在编写一个代码,其中有一个 class 带有属性分子和分母的分数。输出应以简化形式显示分数。例如20/100 应显示为 1/5。
我已经尝试了下面的代码,但出现如下类型错误:
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
class fraction:
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
if (self.__deno==0):
print("Fraction not possible")
exit()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("The simplified fraction is")
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
我不知道如何解决这个错误。请帮助我,因为我是 Python 的新手并且想建立强大的基础知识。
问题出在这个函数定义中:
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
else
子句没有 return
语句。 (此外,else
子句可以是 implicit 而不是 explicit。)而是尝试:
def __GCD(self, a, b):
if b == 0:
return a
return self.__GCD(b, a % b)
我正在编写一个代码,其中有一个 class 带有属性分子和分母的分数。输出应以简化形式显示分数。例如20/100 应显示为 1/5。 我已经尝试了下面的代码,但出现如下类型错误:
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
class fraction:
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
if (self.__deno==0):
print("Fraction not possible")
exit()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("The simplified fraction is")
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
我不知道如何解决这个错误。请帮助我,因为我是 Python 的新手并且想建立强大的基础知识。
问题出在这个函数定义中:
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
else
子句没有 return
语句。 (此外,else
子句可以是 implicit 而不是 explicit。)而是尝试:
def __GCD(self, a, b):
if b == 0:
return a
return self.__GCD(b, a % b)