2016年3月23日 星期三

[python] python 3.4 method 方法解釋 (print out all methods inside an object)

之前說過在python 中


a=5 這行

其中

a 是名稱
5 是一個整數type 的物件

而 這裡要講的方法 (method) 就是

=>這個物件裡可以使用的function.

引用的方式是   「物件.方法名稱(帶入參數 if needed)」

ex: a.len() 就是引用int 物件中的 len() 方法

a=[1,2]

a.append(3) 表示用a.append() 這個fun, 帶入3, 就是把3加入原本a list 物件的尾巴


所以
1.不同型別的物件, 有已經存在的方法(利用dir(物件) 可以印出來看有哪些可用)
ex:
a=[1,2] #list
print (dir(a))

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
[Finished in 0.1s]

2.build in function 也是一種方法
 ex:
a=[1,2,3]
原本用內建fun求長度
len(a)

直譯器看到會轉成
a.__len()__
來作, 所以其實build in function, 是去找當下的物件的method來實作


3.運算子 也是一種方法 ex: + - * /
ex: x+y  => x.__add__(y)







沒有留言:

張貼留言