Reputation: 13
I've been trying to override the first input for fullname
under object "Pete Tong" and change it to "James Milner" using the split
function.
However, when I run the below code, all output except for printing of the fullname()
returns the "Pete Tong" first and last name, which I was trying to change for all accesses. Any idea why? I thought it should be printing all as "James Milner" with the override.
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)
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
emp_1 = Employee('Pete', 'Tong')
emp_1.fullname = 'James Milner'
print emp_1.first
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
Upvotes: 0
Views: 57
Reputation: 77857
You haven't stated so explicitly, but I suspect that you're running Python 2 on a feature that works only in Python 3.
The one print
without parentheses implies that you're running this with Python 2. setter
works only in Python 3. That also explains how another user can get James
from your code (after fixing that one print).
To fix this in Python 2, you need your class to inherit from the mother-of-all, object
:
class Employee(object):
Python3 does this automatically; Python 2 does not.
Upvotes: 1
Reputation: 2375
In order to for properties to work you need to use new style classes which inherit from object, so declare your class like this, it will work
class Employee(object):
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)
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
emp_1 = Employee('Pete', 'Tong')
emp_1.fullname = 'James Milner'
print emp_1.first
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
Upvotes: 0
Reputation: 24052
The problem is that you're using Python 2, and your class is not inheriting object
. You can either (a) Use Python 3, or (b) Change the class definition to:
class Employee(object):
which will work in both Python 2 and Python 3.
Upvotes: 1