Python字符串拆分 - 属性错误

时间:2017-05-09 07:30:31

标签: python

为什么在尝试在空间上拆分字符串full_name并将其分配给两个变量时会出现属性错误?

class Person(object):
    def __init__(self, full_name):
        """Person initializer"""
        self.first_name, self.last_name = full_name.split()

    @property
    def first_name(self):
        return self.first_name

    @property
    def last_name(self):
        return self.last_name


if __name__ == '__main__':
    swadhi = Person("Swadhikar Chandramohan")
    print swadhi.first_name
    print swadhi.last_name

错误:

C:\Python27\python.exe C:/Users/swadhi/Documents/test/tutorial/inheritance.py
Traceback (most recent call last):
  File "C:/Users/swadhi/Documents/test/tutorial/inheritance.py", line 18, in <module>
    swadhi = Person("Swadhikar Chandramohan")
  File "C:/Users/swadhi/Documents/test/tutorial/inheritance.py", line 6, in __init__
    self.first_name, self.last_name = full_name.split(' ')
AttributeError: can't set attribute

3 个答案:

答案 0 :(得分:3)

无需在此使用property

class Person(object):
    def __init__(self, full_name):
        """Person initializer"""
        self.first_name, self.last_name = full_name.split()

if __name__ == '__main__':
    swadhi = Person("Swadhikar Chandramohan")
    print swadhi.first_name
    print swadhi.last_name

答案 1 :(得分:2)

您没有声明属性的setter。 因此,该属性是只读的,您无法修改它。

要解决此问题,请按以下方式添加setter方法:

@property
def last_name(self, value):
    self._last_name = value
@property
def first_name(self, value):
    self._first_name = value
@last_name.setter
def last_name(self, value):
    self._last_name = value
@first_name.setter
def first_name(self, value):
    self._first_name = value

答案 2 :(得分:0)

class Person(object):
    def __init__(self, full_name):
        """Person initializer"""
        self._first_name, self._last_name = full_name.split()

    @property
    def first_name(self):
        return self._first_name


    @property
    def last_name(self):
        return self._last_name

if __name__ == '__main__':
    swadhi = Person("Swadhikar Chandramohan")
    print swadhi.first_name
    print swadhi.last_name

如上所述,确保&#34; _&#34;在定义类属性时以属性名称作为前缀。