【问题标题】:How to read the object name from memory?如何从内存中读取对象名称?
【发布时间】:2021-08-26 03:56:47
【问题描述】:

我写了一个简单的类代码,如下所示。

class Fridge:

def __init__(self):
    self.isOpened = False
    self.foods = []

def open(self):
    self.isOpened = True

def put(self, thing):
    if self.isOpened:
        self.foods.append(thing)

def close(self):
    self.isOpened = False

class Food:
    pass

然后导入模块...

import class_practice as fridge

f = fridge.Fridge()
apple = fridge.Food()
elephant = fridge.Food()

f.open()
f.put(apple)
f.put(elephant)

print(f.foods)

打印输出是

[<class_practice.Food object at 0x7fe761fce5f8>, <class_practice.Food object at 0x7fe761fce710>]

在这种情况下,如果我想打印出f.foods作为[apple, elephant]的对象名,

我该怎么办?

##Revised##

我想从中提取数据

[<class_practice.Food object at 0x7fe761fce5f8>, <class_practice.Food object at 0x7fe761fce710>] 

如 ['apple', 'elephant'] 的形式。

就像,

a = 'hello'
b = id(a)
print(ctypes.cast(b, ctypes.py_object).value)

然后,结果是'hello'

【问题讨论】:

    标签: python class object memory instance


    【解决方案1】:

    将值存储在实例属性中,并从__repr__ dunder 方法返回:

    class Food:
        def __init__(self, value):
            self.value = value
         
        def __repr__(self):
            return self.value
    

    在构造Food时需要传递值:

    apple = fridge.Food("apple")
    elephant = fridge.Food("elephant")
    

    【讨论】:

      【解决方案2】:

      或尝试以下方法:

      class Fridge:
      
          def __init__(self):
              self.isOpened = False
              self.foods = []
      
          def open(self):
              self.isOpened = True
      
          def put(self, thing):
              if self.isOpened:
                  self.foods.append(thing)
      
          def close(self):
              self.isOpened = False
      
      class Food:
          def __init__(self, value):
              self.value = value
           
          def __repr__(self):
              return self.value
      
      import class_practice as fridge
      f = fridge.Fridge()
      f.open()
      f.put(fridge.Food('apple'))
      f.put(fridge.Food('elephant'))
      print(f.foods)
      

      输出:

      [apple, elephant]
      

      【讨论】:

      • 感谢您的回复,有没有办法从0x7fe761fce5f8获取存储的数据?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多