0

first, sorry for my english, I'm french ! I am in the process of creating an account (class) and connecting to it. I use a file where I put my data.

I have a question about my code below (I am a python beginner) Code :

import random
import string


#Définition des classes et des fonctions
class compte:

  def __init__(self, user, mdp):
    self.user = user
    self.mdp = mdp
    self.poids = "not defined"
    self.taille = "not defined"
    self.IMC = "not defined"
    self.test = 1
    #self.adresse = adresse
    self.salle_attribuée = "not defined"
    #self.objectif = objectif


  def cIMC(self):
    print("ok")


def create():
  chaine_minuscule = string.ascii_lowercase
  id_compte = "".join(random.choice(chaine_minuscule) for i in range(5))
  num = id_compte
  user = input("Username: ")
  mdp = input("Password: ")
  id_compte = compte(user, mdp)
  f = open("users.txt", "a")
  texte = [num, "|", id_compte.user, "|", id_compte.mdp]
  for t in texte:
    f.write(t)
  f.write('\n')
  print('\n------------Vous avez bien créé votre compte : ------------\n')
  print("Username = ", id_compte.user, "\nPassword = ", id_compte.mdp)


def login():
  user = input("Username: ")
  mdp = input("Password: ")
  f = open("users.txt", "r")
  for line in f.readlines():
    nbr, us, pw = line.strip().split("|")
    if (user == us) and (mdp == pw):
      print("\nLogin successful!")
      return True, nbr
  print("Wrong username/password")
  return False


connection = False
create()
while True:

  while connection == False:
    connection = login()
    print(connection[1])
    connection[1].cIMC()
  afficher_menu()

Here is the file in which I put the names of the classes, the user names and the passwords: enter image description here

I then get the following error: "Attribute error : 'str' object has no attribute 'cIMC'" And it seems logical because I put in my file a str and not the class. How can I solve this problem and get my class with its id in the file? Thank you in advance!

  • If you really want to save a class INSTANCE you want to use pickle, have a look at this: https://stackoverflow.com/questions/2345151/how-to-save-read-class-wholly-in-python But you can save only the data into a file (like you do now) and then re-instantiate your object using loaded data. Also DO NOT use your natural language no matter the nationality, English is the standard for code, DO use context managers to operate on files, DO NOT call variables with abbreviations as they depend on context, which is by no means understandable for your potential co-workers. – Gameplay Dec 10 '22 at 17:18

0 Answers0