---
# System prepended metadata

title: 為何需要python裡的`self`
tags: [python]

---

# 為何需要python裡的`self`
###### tags: `python`
> [stackoverflow: What is the purpose of the word 'self'?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self)

1. Python 語法蜜糖. 代表屬於一個Class的Object它自己,舉例來說有個class `ClassA` 有定義一個function `methodA`
    - `methodA`
        ``` python
        def methodA(self, arg1, arg2)
         # do something
        ```
    - 而又有個 object `ObjectA` 是`ClassA`的instance,當`ObjectA`要使用`methodA`時,程式會這樣寫:
        ``` python
        ObjectA.methodA(arg1,arg2)
        ```
    - 但python內部會轉換成這樣: 而`self`就代表`ObjectA`它自己
        ``` python
        ClassA.methodA(ObjectA, arg1, arg2)
        ```
    
2. 動態"加入"([Rossum用Poke這個詞](http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html))任何function進一個Class
    - 第10,11行的global function中,用`vector_length`,用`self`也行,只不過就要把function寫進class裡比較好,如:
        ``` python
        class vector:
            def __init__(self,x,y):
                self.x=x
                self.y=y
            def length_in_class(self):
                return math.sqrt(self.x ** 2 + self.y ** 2)
        ```
    - 第18行`my_vector.length_in_class()`,call function記得要有`( )`不然output變成:
        ```
        <bound method length_global of <__main__.Vector object at 0x7f9f50f57a20>>
        ```
    ``` python=
    import math

    # vector Class沒有定義長度計算function
    class Vector:
        def __init__(self,x,y):
            self.x=x
            self.y=y

    # 定義global function,而非Class function
    def length_global(vector_self):
        return math.sqrt(vector_self.x ** 2 + vector_self.y ** 2)

    # Poke the method into Vector Class
    Vector.length_in_class = length_global

    # test
    my_vector=Vector(3,4)
    print(my_vector.length_in_class())
    ```
    
        