[英]If a function (that's outside of the class) needs to use a method from a class, how do I call the method?
[英]How do i call a function that's inside a class from outside of the class?
所以我试图从 PyCharm 中的“帐户”class 外部访问 function“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)`
在 class 之外添加这两行
a = Account("username", "password")
a.saveuserdata()
需要在saveuserdata
的实例上调用 saveuserdata function。
# Create instance
acc = Account("blah", "blah")
# Call function
acc.saveuserdata()
这是以下的简写:
acc = Account("blah", "blah")
Account.saveuserdata(acc)
也许您没有任何使用帐户的 object。 您应该调用从 class 继承的 object 上的方法,而不是 class 本身。 需要更多信息才能确切知道您的问题是什么。
你有两个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.