【发布时间】:2020-07-24 03:42:15
【问题描述】:
我对@987654324@ 中的OOP 很陌生,我喜欢它的工作方式。所以我用它做了很多实验。我正在尝试构建一个Freelancer class,它允许用户使用username 在平台上注册,但会检查数据库中是否不存在username。
这是我的工作方法:
class Freelancer:
"""Leaving this blank for now while I explore the functionality """
number_of_sales = 0
available_niches = ["Graphic design", "Art", "Data Analysis", "Music", "Business", "Writing and Translations"]
usernames = []
def __init__(self, username):
self.username = _check_username(username)
def _check_username(self, username):
if self.username in Freelancer.usernames:
print("This username already exist on our database, consider choosing another one")
else:
self.username = username
Freelancer.usernames.append(self.username)
print("You have successfully setup a username on our platform")
在这里测试这个类和方法:
David = Freelancer("dave23")
给我以下错误:
NameError: name '_check_username' is not defined
我想在我的class initialization 中应用private methods。这可能吗?
【问题讨论】:
-
需要:
self.username = self.__check_username(username)即需要“自我”。 call methods within class。需要__(即双破折号)将方法设为私有Private Methods -
太棒了!谢谢!
标签: python class oop static-methods python-class