object()有什么用? [英] What is object() good for?

查看:146
本文介绍了object()有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎么可能

class EmptyClass:
    def __init__(self):
        pass

e = EmptyClass()
e.a = 123

o = object()
o.a = 123

不会( AttributeError:'object'object没有属性'a')而

print isinstance(e, object)
>>> True

什么是 object()那么,当您不能像这样使用它时呢?

What is object() good for then, when you cannot use it like this?

推荐答案

您不能将属性添加到 object 的实例,因为 object 没有 __ dict __ 属性(用于存储属性)。从文档

You cannot add attributes to an instance of object because object does not have a __dict__ attribute (which would store the attributes). From the docs:


类对象

返回一个新的无特征对象。 对象是所有类的基础。它具有所有Python类实例通用的方法。
此函数不接受任何参数。

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

注意:
object 没有 __ dict __ ,因此您不能将任意属性分配给 object 类的实例。

Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

object 确实有其用途:


  1. 如上所述,它充当Python中所有对象的基类。您看到和使用的所有内容最终都取决于对象

您可以使用对象创建完全唯一的前哨值。使用和不是 对其进行测试只会返回 True 当给出确切的 object 实例时。

You can use object to create sentinel values which are perfectly unique. Testing them with is and is not will only return True when an exact object instance is given.

在Python 2.x中,您可以(应该)从对象继承以创建新式类。新型类具有增强的功能和更好的支持。请注意,所有类在Python 3.x中都是新样式。

In Python 2.x, you can (should) inherit from object to create a new-style class. New-style classes have enhanced functionality and better support. Note that all classes are automatically new-style in Python 3.x.

这篇关于object()有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆