python语法:类中object的用法

假如定义两个类,一个带object,一个不带object,会不会有差别呢?

class Cat:
    name = "mao"
class Dog(object):
    name = "gou"

x=Cat()
y=Dog()
print("Cat",dir(x))
print("Dog",dir(y))

然而结果却是一摸一样的:

Cat ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
Dog ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

因为我使用的是python3版本,已经默认帮你加载了object了(即使没有写上object)。所以python3版本加不加object没有区别。

如果是python2版本呢?
代码:

class Cat:
    name = "mao"
class Dog(object):
    name = "gou"

x=Cat()
y=Dog()
print("Cat",dir(x))
print("Dog",dir(y))

结果如下:

Cat ['__doc__', '__module__', 'name']
Dog ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

Cat类很明显能够看出区别,不继承object对象,只拥有了_ doc _, _ module _和自己定义的name变量, 也就是说这个类的命名空间只有三个对象可以操作.
Dog类继承了object对象,拥有了好多可操作对象,这些都是类中的高级特性。

综上:大家基本上使用的是python 3.x版本,所以代码编写class的时候带上或者不带上object没有区别。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值