gpt4 book ai didi

python - python类声明中的对象参数

转载 作者:行者123 更新时间:2023-12-05 06:26:14 24 4
gpt4 key购买 nike

python类中对象的概念

在阅读 Python 中的旧式和新式类时,术语对象多次出现。究竟什么是对象?它是基类还是仅仅是一个对象或一个参数?

例如:

在 python 中创建类的新样式

class Class_name(object):
pass

如果对象只是另一个类,它是 Class_name(继承)的基类,那么在 python 中什么将被称为对象?

最佳答案

来自 [Python 2.Docs]: Built-in Functions - class object (强调是我的):

Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes.

您还可以查看 [Python]: New-style Classes (和引用的 URL)了解更多详情。

>>> import sys
>>> sys.version
'2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>>
>>> class OldStyle():
... pass
...
>>>
>>> class NewStyle(object):
... pass
...
>>>
>>> dir(OldStyle)
['__doc__', '__module__']
>>>
>>> dir(NewStyle)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>>
>>> old_style = OldStyle()
>>> new_style = NewStyle()
>>>
>>> type(old_style)
<type 'instance'>
>>>
>>> type(new_style)
<class '__main__.ClassNewStyle'>

在上面的例子中,old_stylenew_style 是实例(或者可以称为对象 ),所以我猜你的问题的答案是:取决于上下文。

关于python - python类声明中的对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56401685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com