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)`
Add these two lines outside class
a = Account("username", "password")
a.saveuserdata()
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)
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.
You have two options:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.