关于Python中的实例变量,我有几个相关的问题。我将把第一个(主要)问题放在代码本身的注释中,然后问相关的问题:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split(',')
return cls(first, last, pay)
emp_str_1 = 'John,Doe,70000'
emp_1 = Employee.from_string(emp_str_1)
print(emp_1.fullname(), emp_1.pay, emp_1.email) #<--- This works
print(emp_1.fullname().pay.email) #<--- Why can't I do this??
另外,为什么错误消息称它为“str object”:
AttributeError:“str”对象没有“pay”属性
emp\u 1不是Employee的一个实例吗?你知道吗
最后一个问题,(这可能只是一个PyCharm问题)PyCharm没有试图在我尝试运行它之前警告我这个代码将被破坏,为什么?你知道吗
在Python中,可以使用+
因为你只是在传递信息。[与此问题无关,只是补充信息:如果要打印整数或布尔值,则除非使用str()显式类型转换它,否则它将失败)
因为“.”运算符用于访问实例方法和变量。你知道吗
如果使用emp\u 1.fullname(),它将调用fullname()方法,该方法将返回一些字符串。你知道吗
但是如果使用emp\u 1.fullname().pay-emp\u 1.fullname()是对该方法的调用,而fullname()方法没有任何类似“pay”的变量。所以正确的使用方法是emp\u 1.pay。你知道吗
我建议用印刷体
相关问题 更多 >
编程相关推荐