close

先說stackoverflow 真是寶庫,全球高手分享經驗及解答,讓問題能得到公開透明且大家可以討論的回答,現在的同學真幸福,碰到疑問一定要到這裡先查查!

再說結論 養成一個好習慣任何的class 宣告時習慣性的加入 def __init__(self,name1,name2,....): 讓它變成class宣告時的"起手式"這邊def __init__代表class宣告時會自動執行的函式,所以也代表所有的instance建立時都有一個全新的開始(所有的狀態及參數獲得初始init)

有幾個我了解的定義請您參考也許可以解決您對於self的一些疑惑

1.class(類)是產生object(物件)的模板 每次class產生之object都可稱為是一個獨立的instance(實例) 所以class是宣告模板不是物件instance才是產出物

參考範例:

Let's say you have a class ClassA 

which contains a method methodA defined as:

class ClassA:

def methodA(self, arg1, arg2):

       # do something

ObjectA=ClassA()

and ObjectA is an instance of this class.

2.既然每個instance都是獨立的個體,所以都要有一個不同於別人的名字,他就是self,那奇怪的是每一個都叫self不是都同名了嗎?別擔心,給予self的動作讓python對於產生的instance給予不同的記憶體位址,就好像每一個instance都有自己門牌號碼以做區別

參考範例:

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.

3.Self要寫,當同一class產生之instance都是獨立的個體,彼此不受影響

參考範例:

class Restaurant(object):  
    bankrupt = False
    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")
#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False
#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True
>>> x.bankrupt
False  

4.self可以不寫,但可能產生的風險是

參考範例:

class A: 
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
 
class A: 
    def __init__(self): 
        self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: []

 

5.一定要是self嗎?不能用其他代替嗎?當然可以,只是第一個參數是保留給代表每一個instance識別用的名詞用,您可以用任何名詞代替,但基於程式的可閱讀性及標準化,還是建議您用self

參考範例:

class A(object):
    def __init__(foo):
        foo.x = 'Hello'
    def method_a(bar, foo):
        print bar.x + ' ' + foo

 

6.很棒的一個圖示說明,當instance產生後,object名稱就會變成為self代替名稱

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.

enter image description here

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 阿丹 的頭像
    阿丹

    python愛玩客

    阿丹 發表在 痞客邦 留言(0) 人氣()