社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

这是用python编写异常的正确方法吗?

anjali pandey • 5 年前 • 1876 次点击  

以下代码是用Python编写异常的正确方法吗?

class Calculator:
    def power(self,n,p):
        self.n=n
        self.p=p
        if self.n>=0 and self.p>=0:
            return self.n**self.p
        else:
            return ("n and p should be non-negative")


myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)   

谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51710
 
1876 次点击  
文章 [ 1 ]  |  最新文章 5 年前
chepner
Reply   •   1 楼
chepner    6 年前

你只是从 power 你可能想提出一个例外。另外,你应该检查一下 n p 之前 修改对象。(我不想进一步解释为什么 权力 正在设置属性。)

class Calculator:
    def power(self, n, p):
        if n < 0 or p < 0:
            raise ValueError("Both arguments should be non-negative")
        self.n = n
        self.p = p
        return self.n ** self.p

myCalculator = Calculator()
T = int(input())
for i in range(T):
    n, p = map(int, input().split())
    try:
        ans = myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)