【发布时间】:2018-12-01 23:40:30
【问题描述】:
我创建了一个名为 Hand 的类和一个对象 h1。我用代码将我的对象的结果写在一个文件(handtest.txt)中:
h1 = Hand(3)
datafile = open('handtest.txt', 'w')
datafile.write(str(h1))
datafile.close()
我想读回文件中的内容并将其另存为另一个对象。但是,当我在文本文件中写入对象时,我已经将格式更改为字符串。如何再次将其另存为对象?是否可以在不使用酸洗和 json 的情况下这样做? 这是我的手类:
from card import Card
import random
"""
Defines class Hand, in file hand.py
"""
class Hand:
"""
One object of class Hand represents a hand of cards
and so one object stores a number of Card objects.
"""
def __init__(self, numCardsInHand):
"""
Initializes a Hand object with numCardsInHand Card objects inside it.
"""
# Creates a list for storing a hand of cards.
self.list = []
# Creates a list for storing bj value.
self.listBJ = []
# Uses a loop to store a hand of cards to a list and stores the bj values of the cards to another list.
for count in range(numCardsInHand):
#call hitMe()
Hand.hitMe(self)
def bjValue(self):
"""
Returns the blackjack value for the whole Hand of cards
"""
BJ = ""
# Sums up all the bj values in self.listBJ and returns it to the bjValue method.
BJ = sum(self.listBJ)
return BJ
def __str__(self):
"""
Calls the __str__( ) method and uses the returned value
from the __str__( ) method as the string that is required.
Returns the local variable in the string method.
"""
# Tranforms the self.list from list type to string type and saves it as a local variable.
all_items = '\n'.join(map(str, self.list))
return all_items
def hitMe(self):
"""
Adds one randomly generated Card to the Hand.
Randomly chooses a rank number and a suit type and save them as local variables.
Uses the variables as the Card argument in an object. Then append the object to the self.list
"""
# Randomly chooses a number from 1-13 and stores it as a local variable.
all_rank = random.randint(1, 13)
# Lists suit types.
random_suit = ['d', 'c', 'h', 's']
# Randomly chooses a suit type in the random_suit list and stores it as a local variable.
all_suit = random.choice(random_suit)
# Uses the local variables as arguments of one object of the class Card and appends the object to the self.list.
self.list.append(Card(all_rank, all_suit))
# Appends all_rank to self.listBJ.
self.listBJ.append(all_rank)
【问题讨论】:
-
这取决于该对象包含的内容。这里没有足够的信息。
标签: python-3.x object text-files readfile writefile