python中object的用法_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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值