python - Python 编码最佳实践
问题描述
处理构造函数中的所有参数是个好主意吗?而不是在实际需要参数的特定方法中处理它们?
方法一:
def __init__(self,name,rollno,dob,city,state,zip):
self.name=name
..
..
self.zip = zip
def address(self):
return self.city+self.state+self.zip
def unique_identifier(self):
return self.name+self.rollno
测试.py
example = Example("Programming","941","1997-09-07","Nashville","TN","37311")
print(example.address())
print(example.unique_identifier())
方法二:
Class Example:
def address(self,city,state,zip):
return self.city+self.state+self.zip
def unique_identifier(self,name,rollno):
return self.name+self.rollno
测试.py
example = Example()
print(example.address("ab","cd","111")
print(example.unique_identifier("Programmer","123")
任何有助于理解哪种方法更适合最佳实践的解释/推理。
解决方案
两者都可以,它只取决于数据是否属于对象(方法 1)或数据是否来自对象外部(方法 2)。它也可以是两者的混合。一个简短的例子:
class Person:
# store data specific to the instance
def __init__(self, name, birthdate, hometown):
self.name = name
self.birthdate = birthdate
self.hometown = hometown
# here I only need data from the instance
def introduce(self):
print("Hello, I am", self.name,
", I come from", self.hometown,
" and was born on ", self.birthdate,
".")
# food shouldn't be part of the Person,
# so it is passed in as an argument
def order_food(self, food):
print("I am ", self.name,
" and would like some ", food, " please.")