【问题标题】:using private method in your constructor python在构造函数python中使用私有方法
【发布时间】:2020-07-24 03:42:15
【问题描述】:

我对@9​​87654324@ 中的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。这可能吗?

【问题讨论】:

标签: python class oop static-methods python-class


【解决方案1】:

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

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

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

【讨论】:

  • 需要双下划线来使方法私有化,否则它仍然可以被公共访问,即bill = Freelancer('bill'); bill._check_username('bill')works see
猜你喜欢
  • 2012-01-02
  • 1970-01-01
  • 2017-07-13
  • 2011-04-20
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多