1

I am having trouble grasping how to create a save file for this team roster. The issue I run into is when I try to create what to save in the txt file. Im not sure why i cant get self.player etc to be written in the code. Based on how the players information is written how should I write the txt file to be saved and loaded?

class teamClass:

    Player = ""
    phone_number = ""
    jersey = ""

    def __init__(self, Player, phone_number, jersey):
        self.Player = Player

        self.phone_number = phone_number

        self.jersey = jersey

    def setPlayer(self, Player):
        self.Player = Player

    def setphone_number(self, phone_number):
        self.phone_number = phone_number

    def setjersey(self, jersey):
        self.jersey = jersey

    def setNewPlayer(self, Player):
        self.setPlayer(Player)

    # accessor methods

    def getPlayer(self):
        return self.Player

    def getphone_number(self):
        return self.phone_number

    def getjersey(self):
        return self.jersey

    def displayData(self):
        print("")

        print("Player Info: ")

        print("------------------------")

        print("Player:", self.Player)

        print("Phone number:", self.phone_number)

        print("Jersey:", self.jersey)
Jack Evans
  • 1,697
  • 3
  • 17
  • 33
JohnnySea
  • 11
  • 1

1 Answers1

0

First, there are quite a few problems with your code:

  • Do not create useless class-attributes and override them using instance-attributes. Use a constructor like __init__(self, name=None, phone=None, jersay=None) instead.
  • Do not use getters and setters like you would in Java. Python assumes that all attributes can be accessed without side-effects; if you truly need a getter/setter for an attribute, use a @property.
  • You do not want a displayData-method. Instead, define a __str__()-method and just call print() on the instance.

Concerning your question: You can use json, toml or just pickle to save your object. Here is a toml library ready for use.

An example using json:

import collections
import json
Player = collections.namedtuple('Player', ('name', 'phone_number', 'jersay'))

# Create a new player instance
p = Player('John Doe', '555-ACME', None)

# Save the player-data to a json-file
with open('thefile.txt', 'wt') as f:
    f.write(json.dumps(p))

# Load it back
with open('thefile.txt', 'rt') as f:
    p2 = Player(*json.loads(f.read()))

# Look, ma! They are the same
assert p == p2
user2722968
  • 13,636
  • 2
  • 46
  • 67