[英]Is it necesarry to pass value to the instance variable through constructor of the class?
[英]Class variable and instance variable in the constructor
我在這里得到了這個例子,我認為這可能是我的問題的一個很好的例子:
class Employee:
def __init__(self ,first ,last ,pay ):
entry_gate = 10;
self.first = first
self.last = last
self.pay = pay
self.email = first+"."+last+"@company.com"
我注意到在一些__init__
函數中,有些變量沒有self.
在變量前面。 我了解所有的self.
變量應該是實例變量。 然后,沒有self.
在構造函數中? 我是否應該將其理解為 class 變量,因為它不指向任何實例? 如果 class 構造函數和實例構造函數都使用__init__
作為 function 名稱,它們之間有區別嗎?
The __init__
function in a class is simply the first function that is called when that class is initialized, hence the function name. __init__
function 中定義的變量沒有任何特殊屬性,除了首先定義。 在這種情況下, __init__
function 定義了一個局部變量entry_gate
並將其賦值為 10。這類似於:
def foo():
entry_gate = 10
在 class 中,此結構保持不變,此外任何self.xxx
變量都綁定到 class 的實例(由self
定義),而非self
變量則沒有。
就分號而言,它沒有太多理由存在於此代碼片段中。 分號可用於表示語句的分隔,但不是必需的。 在這種情況下,分號的作用是:
def __init__(self, first, last, pay):
entry_gate = 10; self.first = first
...
要更深入地了解分號,我會向您指出這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.