class Parent(object):
def __init__(self, name, id, basic_salary):
self.name = name
self.id = id
self.basic_salary = basic_salary
def calculate(self):
return (0.1 * self.basic_salary) + (0.2 * self.basic_salary) + self.basic_salary
class Child(Parent):
pass
c = Child("Rupali", 134, 34567)
print("Employee : {0.name} \t ID : {0.id} \t Gross Salary : {0.calculate}".format(self))
错误:打印("员工:{0.name} \ t ID:{0.id} \ t总薪水:{0.calculate}" .format(self)) NameError:name' self'未定义
我希望程序以下列方式打印它: 员工:Rupali ID:134工资总额:45677 怎么做?
答案 0 :(得分:1)
您的print语句格式错误。阅读docs
class Parent(object):
def __init__(self, name, id, basic_salary):
self.name = name
self.id = id
self.basic_salary = basic_salary
def calculate(self):
return (0.1 * self.basic_salary) + (0.2 * self.basic_salary) + self.basic_salary
class Child(Parent):
pass
c = Child("Rupali", 134, 34567)
print("Employee : {} \t ID : {} \t Gross Salary : {}".format(c.name,c.id,c.calculate()))
答案 1 :(得分:1)
您正在混合使用不同类型的字符串格式。尝试:
c = Child("Rupali", 134, 34567)
print(f"Employee : {c.name} \t ID : {c.id} \t Gross Salary : {c.calculate()}")
# Employee : Rupali ID : 134 Gross Salary : 44937.1
这利用了Python 3.6的新f-strings
。
如果您不使用Python 3.6,则可以使用其他答案的.format
方法。
请注意,您可以覆盖班级__str__
方法为您执行此操作。
class Child(Parent):
def __str__(self):
return f"Employee : {self.name} \t ID : {self.id} \t Gross Salary : {self.calculate()}"
c = Child("Rupali", 134, 34567)
print(c)
# Employee : Rupali ID : 134 Gross Salary : 44937.1