【问题标题】:Python returning from class [closed]Python从类返回[关闭]
【发布时间】:2016-12-29 18:14:44
【问题描述】:
class Customer:  #at this part ı defined the class for the customers in the file
    def __init__(self, Name, Surname, Age, Balance):
        self.name = Name;
        self.sname = Surname;
        self.age = Age;
        self.balance = Balance;

    def __str__(self):
        return("Hello, "+str(self.name)+" "+str(self.sname)+" You have "+ str(self.balance)+" dollars in your account.");

你好,上面可以看到我的课

我的目标 - 询问用户姓名并在课堂上获得 str 部分。 我正在从 csv 文件中获取有关客户的信息。

ans = input("name")
ans2 = input("surname")


a = Customer(ans,ans2)
print(a)

在这部分中,我尝试完成上面解释的部分,但无法使代码正常工作。

【问题讨论】:

  • 如果你执行它会发生什么?请提供输出
  • 看起来您只用两个参数调用 Customer,但它需要 4 个?
  • ';'行尾不需要,毕竟是Python。

标签: python string class printing


【解决方案1】:

您必须定义类实例应该具有的所有其他属性,即姓名、姓氏、年龄、平衡,而您只给出了姓名和姓氏。 Python 还将期望您在 __init__ 中提供的所有其他属性

以此为例:

Age = input("age") #add these to take input too
Balance = input("balance") #add these to take input too
a = Customer(ans,ans2, Age, Balance)

【讨论】:

    【解决方案2】:

    好吧,如果您的值有时应该为空,请设置一些不需要的值,例如:

    class Customer:
        def __init__(self, Name, Surname, Age=None, Balance=None): # specify the values which would be left as blank
            self.name = Name;
            self.sname = Surname;
            self.age = Age;
            self.balance = Balance;
    # another code here
    

    那么,如果你只将部分数据传递给类构造函数,你仍然会得到一个没有任何错误的工作类实例:

    >>> a = Customer('Name', 'Surname')
    >>> a.Name
    'Name'
    >>> a.Surname
    'Surname'
    >>> a.Age
    >>>         # we got None here
    

    当然,您也可以使用键盘输入来输入值,这不是您的csv数据文件提供的,而是使用input()函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2014-02-12
      • 2013-02-18
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多