[英]How do i call a function that's inside a class from outside of the class?
So i'm trying to access the function "saveuserdata" from outside the "Account" class in PyCharm.所以我试图从 PyCharm 中的“帐户”class 外部访问 function“saveuserdata”。 But it keeps saying
Unresolved reference 'saveuserdata'
但它一直说
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在 class 之外添加这两行
a = Account("username", "password")
a.saveuserdata()
The saveuserdata
function needs to be called on an instance of the class.需要在
saveuserdata
的实例上调用 saveuserdata function。
# 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.也许您没有任何使用帐户的 object。 You should call the method on the object that inherits from your class, not the class itself.
您应该调用从 class 继承的 object 上的方法,而不是 class 本身。 Need more info to know exactly what your problem is.
需要更多信息才能确切知道您的问题是什么。
You have two options:你有两个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.