I have a few related questions about instance variables in Python. I will put the first (main) question in a comment inside the code itself and ask the related ones afterwards:
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??
Also, why is it called a "str object" by the error message:
AttributeError: 'str' object has no attribute 'pay'
Isn't emp_1 an instance of Employee?
Last question, (this may just be a PyCharm issue) PyCharm does not attempt to warn me that this code will break before I try and run it, why?
"abc".emailwould you expect that to work?emp1.fullname().payis a string, so then you try to get the .email attribute of a string. Pycharm can't tell you this is broken because it doesn't infer the type of.pay