當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python object()用法及代碼示例

在python中,我們為其分配值/容器的每個變量都被視為一個對象。Object 本身就是一類。讓我們討論一下該類的屬性並演示如何將其用於日常編程。

用法: object()
參數: None
返回: Object of featureless class. Acts as base for all object

代碼1:演示object()的工作

# Python 3 code to demonstrate  
# working of object() 
  
# declaring the object of class object 
obj = object() 
  
# printing its type  
print ("The type of object class object is:") 
print (type(obj)) 
  
# printing its attributes 
print ("The attributes of its class are:") 
print (dir(obj))

輸出:


The type of object class object is:

The attributes of its class are:
[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]

object()的屬性
  • 對象類的對象不能向其添加新屬性。
  • 這些對象是唯一製作的,彼此不等同,即一旦比較,就不會返回true。
  • 對象充當我們製作的所有自定義對象的基類。

代碼2:演示object()的屬性

# Python 3 code to demonstrate  
# properties of object() 
  
# declaring the objects of class object 
obj1 = object() 
obj2 = object() 
  
# checking for object equality 
print ("Is obj1 equal to obj2:" + str(obj1 == obj2)) 
  
# trying to add attribute to object 
obj1.name = "GeeksforGeeks"

輸出:

Is obj1 equal to obj2:False

異常:

Traceback (most recent call last):
  File "/home/46b67ee266145958c7cc22d9ee0ae759.py", line 12, in 
    obj1.name = "GeeksforGeeks"
AttributeError:'object' object has no attribute 'name'


相關用法


注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python | object() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。