Reputation: 11
I wrote a simple class code like below.
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
And then import the module...
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)
The print output is
[<class_practice.Food object at 0x7fe761fce5f8>, <class_practice.Food object at 0x7fe761fce710>]
In this case, if I want to print out f.foods
as the object name of [apple, elephant]
,
how could I do?
##Revised##
I want to extract data from
[<class_practice.Food object at 0x7fe761fce5f8>, <class_practice.Food object at 0x7fe761fce710>]
as the form of ['apple', 'elephant'].
It is like,
a = 'hello'
b = id(a)
print(ctypes.cast(b, ctypes.py_object).value)
And then, the result is 'hello'
Upvotes: 1
Views: 140
Reputation: 71620
Or try the following:
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)
Output:
[apple, elephant]
Upvotes: 0
Reputation: 5825
Store the value in a instance attribute, and return it from the __repr__
dunder method:
class Food:
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value
You will need to pass the value when constructing Food
:
apple = fridge.Food("apple")
elephant = fridge.Food("elephant")
Upvotes: 1