要返回空对象,Python 中使用 object() 方法。这是所有类的基础。让我们看看object()的语法。不包含任何参数 -
'object()
无法将新属性或方法添加到此对象。它本身充当所有属性和方法的基础,任何类的默认值。
创建一个空对象
示例
在此示例中,我们将使用 object() 方法创建一个空对象 -
'# Create an empty object
ob = object()
# Display the empty object
print("Object = ",ob)
输出
'Object = <object object at 0x7f2042320f00>
创建一个空对象并显示属性
示例
在此示例中,我们将使用 object() 方法创建一个空对象。我们将使用 dir() 方法显示属性 -
'# Create an empty object
ob = object()
print(dir(ob))
输出
'['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
比较两个空对象
示例
让我们看看比较两个空对象时会发生什么。他们将返回 False -
'# Create two objects
ob1 = object()
ob2 = object()
# Comparing both then objects
print("Are both the objects equal = ",str(ob1 == ob2))
输出
'Are both the objects equal = False