如果已经调用了一个类的对象,可以给它赋值吗? Python 3

时间:2018-11-27 15:49:50

标签: python python-3.x class reference

CREATE OR REPLACE FUNCTION dcr_report_demo(finid integer,
                                           prdid integer,
                                           comp_cd character varying,
                                           divid integer,
                                           fsid integer)
  RETURNS table(report_no integer, 
                dcr_date date, 
                work_type text, 
                hq_type text, 
                rout_name text, 
                .... rest of the columns ...) 
  LANGUAGE sql
AS $BODY$
  SELECT hd.report_no,
         hd.dcr_date,
         ... 
  FROM ...
    JOIN ...
  WHERE hd.period_id = prdid
    AND hd.fin_year_id = finid
    AND hd.company = comp_cd
    AND fm.company_cd = comp_cd
    .... 
  ORDER BY fm.fs_name,
           dcr_date;
$BODY$;

使用class myClass: pass myClass() 创建一个myClass()类型的对象。像这样调用后,如何将对象精确分配给变量?因为如果在调用myClass()之后添加myClass,将创建另一个对象,而a = myClass()将指向该另一个对象。

3 个答案:

答案 0 :(得分:0)

如果仅调用类构造函数而不将结果分配给变量,则不会创建引用。甚至垃圾收集器都不知道此类的实例。

import gc

class myClass:
    pass

myClass() 
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )

a = myClass()
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )
del a

gc.disable() # even disabling the garbage collector will not make a difference
myClass()
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )

输出:

[] []
['a'] [<__main__.myClass object at 0x00000000046026D8>]
[] []

但是,您可以让类跟踪引用本身:

import gc

class myClass:
    ref = []
    def __init__(self):
        myClass.ref.append(self)

myClass()
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )

a = myClass()
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )
del a

gc.collect() # force garbage collection
print( [o for o,t in globals().items() if isinstance(t, myClass)], [o for o in gc.get_objects() if isinstance(o, myClass)] )

输出:

[] [<__main__.myClass object at 0x00000000048226D8>]
['a'] [<__main__.myClass object at 0x00000000048226D8>, <__main__.myClass object at 0x0000000004890860>]
[] [<__main__.myClass object at 0x0000000004890860>, <__main__.myClass object at 0x00000000048226D8>]

注意:这样,垃圾回收器将从不删除该类的实例,即使该变量被删除,只要该类保留对该实例的引用即可!

答案 1 :(得分:0)

class MyClass:
    instances = []

    def __init__(self, name: str):
        self.name = name

        MyClass.instances.append(self)

    def printName(self):
        print("My name is " + self.name)

    def setName(self, name: str):
        self.name = name


a = MyClass("Joshua")

a.printName()   # Outputs 'My name is Joshua'

b = a

b.printName() # Outputs 'My name is Joshua'

b.setName("DeepSpace")

a.printName()   # Outputs 'My name is DeepSpace'
b.printName()   # Outputs 'My name is DeepSpace'

MyClass.instances[0].printName()    # Outputs 'My name is DeepSpace'

使用b = a时,这意味着b将指向与a相同的存储位置,这是因为您的类是可变的。您可以通过将实例作为列表存储在基类中来手动存储实例以供以后引用。

答案 2 :(得分:-3)

由于CPython垃圾回收,因此无法执行以下操作:

myClass()
a = lastObjectCreated()

但是没有用例,并且100%不可能(至少在CPython中),因为对象在创建后就被销毁,因为没有变量指向该对象(没有变量引用该类)。


弱引用是不会阻止对象删除的引用。这样,我们可以目睹一个对象被删除,就像这样:

class myClass:
    pass

import weakref

def catch_deletion(object):
    print('Object was deleted')

weakref.ref(myClass(), catch_deletion)
#Output: Object was deleted

那证明它真的消失了。