May-09-2019, 06:58 AM
Hi, I don't know if my topic makes any sense but what I'm trying to say is, I'm made a class
I tried doing this
I tried printing the variable z and it shows what I'm expecting
P.S.
If my question is kinda noob I'm so sorry since I'm really a beginner with programming in general so please bear with me. Thank you.
class Users:
def __init__(self, fname, lname, bday, username, password, domain='gmail'):
self.fn = fname
self.ln = lname
self.bd = bday
self.un = username
self.pw = password
self.dom = domain
def fullname(self):
return(self.fn + ' ' + self.ln)
def email(self):
return(self.fn.lower() + '_' + self.ln.lower() + '@' + self.dom + '.com')
def show_info(self):
return(
f''' The following is the info for user {self.un}:
First Name: {self.fn}
Last Name: {self.ln}
Birthdate: {self.bd}
Email: {self.fn}_{self.ln}@{self.dom}.com
''')and I created an object under that class user_1 = Users('Adam', 'Smith', '1/1/2000', 'adam1100', 1234)As you see, my class is like a personal info sheet. My question is, how can I save this particular object to an external file (like a text or a binary file) which could be loaded as is (remain as a "User" class) the next time I ran the code. Like the external file should become a database or something. I tried doing this
def save_info(self):
x = f"'{self.fn}', '{self.ln}', '{self.bd}', '{self.un}', '{self.pw}', '{self.dom}'"
with open('users', 'r+') as data:
data.write(x)which is a function under the class I made, yes it does save in a file however, whenever I'm reading the file using this @staticmethod
def load_info():
with open('users', 'r+') as data:
return(data.read())and running this outside the code block of the classz = Users.load_info() user_1 = Users(z)its returning an error
Error:Traceback (most recent call last):
File "c:\Users\***\Desktop\Python\Test\test.py", line 39, in <module>
user_1 = Users(z)
TypeError: __init__() missing 4 required positional arguments: 'lname', 'bday', 'username', and 'password'I think what the interpreter is telling is that it can't recognize the output from the text file as a valid __init__ of the class (since it is telling me that the code does not have any positional arguments)I tried printing the variable z and it shows what I'm expecting
Output:'Adam', 'Smith', '1/1/2000', 'adam1100', '1234', 'gmail'Can you please enlighten me. I'm confused with creating classed that's why I'm focusing on it. Thanks.P.S.
If my question is kinda noob I'm so sorry since I'm really a beginner with programming in general so please bear with me. Thank you.
