我發明了另一個例子,它顯示了在第二種風格中所有課程的動機。顯然,這是大量過度設計的。讓我們假設除了你的調用之外,還有一些其他的代碼會使用這個類去做一些其他的事情,而不是隻調用一個函數,所以這個複雜的接口是合理的。
class MyClass(object):
def __init__(self):
self.get_config()
self.validate_config()
self.hello()
def get_config(self):
self.message = "hello"
def validate_config(self):
# I'm not claiming this is good practice, just
# an example of multiple methods that share state
if not self.message:
raise Exception()
def hello(self):
print(self.message)
if __name__ == "__main__":
MyClass()
那麼我們在這裏有什麼?基本上,您正在使用MyClass
的調用,而不是爲了創建一個對象(儘管它確實會這樣做並且放棄它),但是卻是爲了執行該對象的方法__init__
。它當然有效,但它不是「自然的」。自然的事情是,如果你想運行「一些東西」,你可以調用一個包含這些東西的函數。你並不特別希望它返回一些你根本不關心的對象。如果東西需要保持一定的狀態,做它的工作,然後就可以處理,你不需要它告訴你在最後的狀態:
class MyClass(object):
def __init__(self):
self.get_config()
self.validate_config()
def get_config(self):
self.message = "hello"
def validate_config(self):
# I'm not claiming this is good practice, just
# an example of multiple methods that share state
if not self.message:
raise Exception()
def hello(self):
print(self.message)
def main():
MyClass().hello()
if __name__ == "__main__":
main()
這看起來更像是你的第一個樣式比你第二,所以在這個意義上我更喜歡第一個。
具有main
函數可能會使它在一些類型的線束(如Python提示符或測試工具)下使用模塊更容易一點。不過這並不是必要的。如果有人想要像__name__ == '__main__'
那樣做,那麼最壞的情況下他們可以複製該來源。
爲什麼要用這個類呢? – user2357112
後者在語義上是錯誤的,因爲構造函數不應該做任何額外的工作,以及初始化對象。如果你真的想避免一個額外的行,你可以使用'MyClass()。hello()'。 –
@ user2357112:爲什麼不呢?該程序顯然更復雜,在函數之間引用'self'變量(除其他之外) – WoJ