【问题标题】:Creating an Object in Python在 Python 中创建对象
【发布时间】:2022-08-18 21:01:18
【问题描述】:

在 python 中,一切都是对象。我有一个困惑,请清除它,查看以下代码:

i=10 # Am I creating an object of <class int> by writing this line of code? Is `i` an object of <class int> in reality?
s=5 #Am I creating another object of <class int> by writing this line of code?

请在代码 cmets 中回答我的两个问题。谢谢

  • 它们是对象,但不可变,因此您的引用将随着您更改对象的值而更改。对于其他对象,引用可以保留在同一个对象上,具体取决于您如何使用它,并且多个引用可以继续指向同一个对象。
  • 我投票结束这个问题,因为这是基本知识。 OP 可以在 Python 文档中找到答案。
  • 您知道一切都是对象,但怀疑 is 是对象 - 也许解释一下原因,以便其他人可以帮助消除混淆。

标签: python class object


【解决方案1】:

您可以使用isinstancetype 轻松验证自己:

i=10
s=5

print(isinstance(i, object))
print(type(i))
print(isinstance(s, object))
print(type(s))

无论他们是不同的可以使用id 检查对象:

print(id(i))
print(id(s))

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2013-02-11
    • 1970-01-01
    • 2014-01-14
    • 2015-04-02
    • 2018-01-16
    • 2010-09-25
    • 2016-10-04
    • 2017-09-29
    相关资源
    最近更新 更多