没有理由实例化所有字段都设置为“无”的对象。
我会检查一下
__init__
像这样:
class PhoneNumber:
def __init__(self, number_raw):
number = int(number_raw) # do not catch exception here, catch it on instantiation
number_str = str(number) # parse to str for slicing
self.areaCode = number_str[0:3] # note no space around slicing indexes
self.exchange = number_str[3:6]
self.line = number_str[6:13]
另外,值得注意的是使用pep-8类变量,所以使用
area_code
而不是
areaCode
.
第二种方式(使用ClassMethod)
如果你需要回来
None
出于某些原因,您可能会发现使用ClassMethod实例化很有用,例如:
class PhoneNumber:
def __init__(self, number_raw):
self.areaCode = number_raw[0:3]
self.exchange = number_raw[3:6]
self.line = number_raw[6:13]
@classmethod
def instantiate_with_checks(cls, number_raw):
try:
int(number_raw)
except ValueError:
return None
# after ensuring that provided variable is valid
return cls(number_raw)
实例化新
PhoneNumber
像这样的对象:
PhoneNumber.instantiate_with_checks(number_raw)
.
第三种方式(使用
__new__
):
class PhoneNumber:
def __init__( self, number_raw ):
self.area_code = number[0:3]
self.exchange = number[3:6]
self.line = number[6:13]
@classmethod
def is_number_valid(cls, number_raw):
try:
int(number_raw)
except ValueError:
return False
return True
def __new__(cls, number_raw):
if cls.is_number_valid(number_raw):
return super().__new__(cls)