Why can not initialize the class?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Aug 22 11:17:53 EDT 2014
Luofeiyu, you are getting stuck on basic questions. Before working with
advanced features like properties, you should learn the simply features.
luofeiyu wrote:
> >>> class Contact(object):
> ... def __init__(self, first_name=None, last_name=None,
> ... display_name=None, email="haha at haha"):
> ... self.first_name = first_name
> ... self.last_name = last_name
> ... self.display_name = display_name
> ... self.email = email
> ... def print_info(self):
> ... print(self.display_name, "<" + self.email + ">" )
> ... def set_email(self, value):
> ... print(value)
> ... self._email = value
> ... def get_email(self):
> ... return self._email
> ... email = property(get_email, set_email)
> ...
> >>>
> >>> contact = Contact()
> haha at haha
>
> why the value in `def set_email(self, value): ` is haha at haha?
> how haha at haha is called to value in `def set_email(self, value): `?
> would you mind telling me the process?
Instead of this complicated example, start with this simple example:
class Contact(object):
def __init__(self, email="haha at haha"):
self.email = email
contact = Contact()
print(contact.email)
Do you understand how contact.email gets set to "haha at haha"?
Now let's make it a bit more complicated:
class Contact(object):
def __init__(self, email="haha at haha"):
self.set_email(email)
def set_email(self, value):
self.email = value
contact = Contact()
print(contact.email)
Do you still understand how contact.email gets set to "haha at haha"?
One final version:
class Contact(object):
def __init__(self, email="haha at haha"):
self.email = email
def _get_email(self):
return self._the_secret_private_email
def _set_email(self, value):
self.self._the_secret_private_email = value
email = property(_get_email, _set_email)
contact = Contact()
print(contact.email)
Now do you understand how contact.email gets set to "haha at haha"?
--
Steven
More information about the Python-list
mailing list