关于Python中的None和null

在很多编程语言中,都有null这个值,作为值赋予给变量。

Python中也有,但是是用None。使用None的原因是:
1)null这个单词不够友好,对初学者来说不好理解。
2)面向对象的语言都倾向用驼峰命名法,None符合驼峰命名法。

在Python中,None是一个对象:
 

>>> print(type(None))
<class 'NoneType'>

什么时候可以用Python的None:
1)用于判断一个函数或者方法是否生效,例如:
 

# pseudocode
import MyDatabase

database_connection = None

# try to connect database
try:
    database_connection = MyDatabase(host, port, user_name, user_password)
except Exception as e:
    pass

if database_connection is None:
    print("fail to connect database")
else:
    print("database connected")

2)检查一个变量是否为None
这点上要特别注意的是:Python中,一般我们用于判断一个变量是否为None有两种方式,一种是is,一种是==。平时可能这两种方式都可以得到正确的结果,但是不建议用== 方式。因为 == 是一个类中的内置函数__eq__,而定义类的时候,是允许重写内置函数的,所以可能因为重写了__eq__,导致使用 == 方式来判断出现错误。例如:
 

# pseudocode
class MyClass:
    def __eq__(self, my_object):
    # No matter what, we return True, which will cause some errors
        return True

my_class = MyClass()

if my_class is None:
    print("my_class is None, using the is keyword")
else:
    print("my_class is not None, using the is keyword")

if my_class == None:
    print("my_class is None, using the == syntax")
else:
    print("my_class is not None, using the == syntax")

以上的伪代码,因为重写了__eq__方法,让它不管在任何时候,都返回True,所以my_class本来不是None的,却被认为是None。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值