【问题标题】:Object has no attribute - Variable name shared between classes对象没有属性 - 类之间共享的变量名
【发布时间】:2018-06-18 00:29:06
【问题描述】:

我需要为 SalesRep 分配一个新帐户,同时更新我的​​ Account 的班级,让 Leslie 作为销售代表。

我收到错误:

'str' object has no attribute 'set_sales_rep'

当我测试以下几行时:

rep_1 = SalesRep('Leslie', 'Knope', ['acct1', 'acct2', 'acct3'])
print(rep_1.add_account('acct4'))

SalesRep类:

class SalesRep(object):

    def __init__(self, first_name, last_name, accounts=None):
        self.first_name = first_name
        self.last_name = last_name
        self._accounts = []

        if accounts:
            self._accounts.extend(accounts)

    def __str__(self):
        return "{self.first_name} {self.last_name}".format(self=self)

    def get_accounts(self):
        return self._accounts

    def add_account(self, account):
        self._accounts.append(account)
        account.set_sales_rep(self)

Account类:

class Account(object):

    def __init__(self, name, sales_rep=None, segments=None):
        self.name = name
        self._sales_rep = sales_rep
        self._segments = []

        if segments:
            self._segments.extend(segments)

    def __str__(self):
        return "{self.name}".format(self=self)

    def get_sales_rep(self):
        return self._sales_rep

    def set_sales_rep(self, sales_rep):
        self._sales_rep = sales_rep

我要做的就是测试 SalesRep 类中的 add_account 是否正常工作,我在 Account 类中定义了“set_sales_rep”。我不确定错误是我在类之间错误地关联了“set_sales_rep”还是我在顶部的print() 函数调用是错误的。

【问题讨论】:

    标签: python python-3.x class object attributes


    【解决方案1】:
    rep_1 = SalesRep('Leslie', 'Knope', ['acct1', 'acct2', 'acct3'])
    print(rep_1.add_account('acct4'))
    

    您正在将字符串而不是帐户对象传递给 add_account。

    创建一个帐户对象acc = Account(name="acc4"),然后将其传递给add_account rep_1.add_account(acc)

    【讨论】:

    • 请注意,修复此问题后,对print() 的以下调用将显示None,因为SalesRep.add_account() 方法不会返回任何内容...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多