0

我很陌生OOPPython我喜欢它的工作方式。所以我用它做了很多实验。我正在尝试构建一个Freelancer class允许用户使用 a 在平台上注册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

我想要一种方法来申请private methods我的class initialization. 这可能吗?

4

1 回答 1

3

在调用私有方法之前你错过了自我。

def __init__(self, username):
    self.username = self._check_username(username)

如果它仍然给出错误,例如:“Freelancer”对象没有属性“用户名”定义用户名变量

于 2020-04-11T12:09:52.937 回答