下面是我以崇高的文字执行的代码段
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp1 = Employee('Aquib', 'Javed')
emp1.email()
emp1.fullname()
print(emp1.fullname)
答案 0 :(得分:0)
您的代码没有正确缩进。
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self): #same level indentation as __init__() or it'll have scope under __init__() method only
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp1 = Employee('Aquib', 'Javed')
emp1.email # Since you've mentioned `email` as property and returning as string, you should just use its property's name
emp1.fullname # same goes here too
print(emp1.fullname)
答案 1 :(得分:0)
阅读有关Short Description of the Scoping Rules?的信息(此处有关类:https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes)
将代码固定为:
# your class definition, all that belongs to it, is indented 1 more then "class .... :"
class Employee:
# method of your class
def __init__(self, first, last):
self.first = first
self.last = last
# property of your class
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
# not part of your class, you are creating an Instance of your class
emp1 = Employee('Aquib', 'Javed')
emp1.email # this returns a string, but you do nothing with it - so it is discarded
emp1.fullname # this returns a string, but you do nothing with it - so it is discarded
print(emp1.fullname) # this prints it