So i'm trying to access the function "saveuserdata" from outside the "Account" class in PyCharm. But it keeps saying Unresolved reference 'saveuserdata'
class Account:
def __init__(self, password, username):
self.password = password
self.username = username
def login(self, x, y):
if x == self.password and y == self.username:
print("Correct, Logging on...")
else:
print("Incorrect username or password, please try again.")
def saveuserdata(self):
with open("user_data.txt", "a ") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read(100)
if len(data) > 0:
file_object.write("\n")
# Append text at the end of file
file_object.write("Username: " self.username " Password: " self.password)`
CodePudding user response:
Add these two lines outside class
a = Account("username", "password")
a.saveuserdata()
CodePudding user response:
The saveuserdata
function needs to be called on an instance of the class.
# Create instance
acc = Account("blah", "blah")
# Call function
acc.saveuserdata()
This is shorthand for:
acc = Account("blah", "blah")
Account.saveuserdata(acc)
CodePudding user response:
Maybe you don't have any object that uses Account. You should call the method on the object that inherits from your class, not the class itself. Need more info to know exactly what your problem is.
CodePudding user response:
You have two options:
- declare an object of class Account, and then call the method on the object,just like upwards.
- declare @classmethod annotation on the class, then call the method on the class.