您指的是默认关键字参数。您在示例中指定它的方式意味着name
在构造函数中是必需的。使其默认的方式(并且能够在构造函数之后设置)如下所示:
class Friend(object):
def __init__(self,name=''):
self.name = name
def set_name(self,name):
self.name=name
def get_name(self):
return self.name
现在您的类可以在没有名称的情况下实例化:
aFriend = Friend()
正如评论中所建议的那样,为基本属性设置 setter 和 getter 并不是“被认为是 pythonic”。但是,如果该属性需要计算,那么您可以将其设为属性:
class Friend(object):
def __init__(self, firstname='', lastname=''):
self.firstname = firstname
self.lastname = lastname
@property
def firstname(self):
return self._first
@firstname.setter
def firstname(self, n):
self._first = n.capitalize()
@property
def lastname(self):
return self._last
@lastname.setter
def lastname(self, n):
self._last = n.capitalize()
@property
def fullname(self):
return "{0} {1}".format(self.firstname, self.lastname)
f = Friend('frank')
f.lastname = 'smith'
f.firstname
# 'Frank'
f.lastname
#'Smith'
f.fullname
#'Frank Smith'