如何在Python中访问未命名的对象

huangapple go评论70阅读模式
英文:

how reach the unnamed object in python

问题

# 第一种方式
class temp:
    def __init__(self, name):
        self.name = name

object1 = temp("abolfazl")
print(object1)

# 第二种方式
class temp:
    def __init__(self, name):
        self.name = name

print(temp("abolfazl"))

这两种方式执行相同的操作(我猜是这样的),即创建一个 temp 类的实例。但如果我们使用第二种方式,我们无法检索该对象,或者我认为是这样。

能否告诉我它们之间的区别是什么?以及 "self" 做了什么,我以为它在第一种方式的代码中与 "object1" 有关,但现在我感到困惑。

英文:
#first way
class temp:
    def __init__(self, name):
        self.name = name

object1 = temp("abolfazl")
print(object1)

#second way
class temp:
    def __init__(self, name):
        self.name = name

print(temp("abolfazl"))


both do the same action(I guess :)), creating the instance of a temp class but if we do in a second way we can't retreive that object or i guess so

could you please tell me what are the differences? and what did "self" do i thought it does something with "object1" in way one code but now I confused

答案1

得分: 1

对象具有引用计数;当引用计数达到 0 时,对象就会被销毁。

在你的第一个示例中,object1 = temp("...") 创建了对象并将其引用计数设为 1:object1 就是该引用。当你将它传递给 print 时,暂时会有两个引用计数,因为 print 参数绑定到该对象,成为第二个引用。一旦 print 返回,参数超出范围,引用计数又减少为 1。

在你的第二个示例中,对 temp 实例的 唯一 引用是 print 中的参数。当 print 返回时,引用计数从 1 降至 0,对象就被销毁。

self 只是绑定到 temp.__init__ 调用期间新实例的参数。

英文:

Objects have a reference count; when the reference count reaches 0, the object is destroyed.

In your first example, object1 = temp("...") creates the object and sets its reference count to 1: object1 is that reference. When you pass it to print, it temporarily has a reference count of two, as the print parameter the object is bound to is a second reference. Once print returns, the parameter goes out of scope and the reference count is decremented back to 1.

In your second example, the only reference to the temp instance is the parameter in print. When print returns, the reference count drops from 1 to 0, and the object is destroyed.

self is just the parameter bound to the new instance for the duration of the call to temp.__init__.

huangapple
  • 本文由 发表于 2023年2月16日 02:19:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定