Python 進擊

dict

  • class dict(iterable, **kwarg)
    Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
>>> d = dict([('a',1), ('b',2), ('a',3)])
>>> d
{'a': 3, 'b': 2}
  • get(key[, default])
    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
>>> d = {'b': 2}

>>> d.get('a')
>>> d.get('b')
2
>>> d.get('a', 1)
1
>>> d
{'b': 2}
  • setdefault(key[, default])
    If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
>>> d = {'b': 2}

>>> d.setdefault('b',3)
2
>>> d.setdefault('a',1)
1
>>> d
{'a': 1, 'b': 2}
>>> d.setdefault('c')
>>> d
{'a': 1, 'b': 2, 'c': None}
  • pop(key[, default])
    If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
>>> d
{'a': 1, 'b': 2}
>>> d.pop('a')
1
>>> d
{'b': 2}
>>> d.pop('a', None)
>>> 
>>> d
{'b': 2}
>>> d.pop('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
  • popitem()
    Remove and return an arbitrary (key, value) pair from the dictionary. If the dictionary is empty, calling popitem() raises a KeyError.

str

  • str.find(sub[, start[, end]])
    Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

  • str.strip([chars])?

  • str.split(sep=None, maxsplit=-1)?

  • str.splitlines([keepends])?

  • str.startswith(prefix[, start[, end]])
    Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

  • str.endswith(suffix[, start[, end]])
    Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

  • str.capitalize()
    Return a copy of the string with its first character capitalized and the rest lowercased.

  • str.lower()
    Return a copy of the string with all the cased characters converted to lowercase.

  • str.upper()
    Return a copy of the string with all the cased characters converted to uppercase

format

  • 1 %s
>>> '/%s/%s' % ('a','b')
'/a/b'

>>> '%(a)s and %(b)s' % {'a': 'apple', 'b':'banana'}
'apple and banana'

__new__() v.s. __init__() v.s. __call__()

  • __new__(): 創(chuàng)建對象
    __init__(): 初始化對象
    __call__(): 對象的調(diào)用

關(guān)系:現(xiàn)有對象的創(chuàng)建,然后有初始化。即先 __new__() 再 __init__(). __init__() 有一個 self 參數(shù),這個就是 __new__() 返回的實例。

  • 看個栗子
class A(object):
    def __init__(self, *arg, **kwarg):
        print("Hi, i'm init!")
        print(self)

    def __new__(cls, *arg, **kwarg):
        print("Hi, i'm new!")
        print(cls)
        return object.__new__(cls, *arg, **kwarg)

    def __call__(self, *arg, **kwarg):
        print("Hi, i'm call!")

if __name__ == '__main__':
    a = A()
    a()

its output:

Hi, i'm new!
<class '__main__.A'>
Hi, i'm init!
<__main__.A object at 0x7f5eeec87b70>
Hi, i'm call!
  • read more
    • object.__new__(cls[, ...])?
    • object.__init__(self[, ...])?
    • object.__call__(self[, args...])?

instance method v.s. @staticmethod method v.s. @classmethod method

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容