PYTHON高階語(yǔ)法

1. 可變參數(shù)*Args**Kwargs

https://www.scaler.com/topics/python/args-and-kwargs-in-python/

*args代表的是一組無(wú)關(guān)鍵字的可變參數(shù)值。**kwargs表示的是一組可變鍵值對(duì),類似字典參數(shù)拢军。當(dāng)對(duì)程序的輸入?yún)?shù)不可預(yù)知或者擴(kuò)展性要求很高時(shí)蒜埋,選擇可變參數(shù)是不錯(cuò)的主意。

*的用法

def multiplyNumbers(*numbers):
    product = 1
    for n in numbers:
        product *= n
    return product

def args_output(*args):
    for arg in args:
        print(arg)

print("product:", multiplyNumbers(4, 4, 4, 4, 4, 4))
args_output(1, "hello", 3.14)

**的用法

def whatTechTheyUse(**kwargs):
    result = []
    for key, value in kwargs.items():
        # result.append("{} uses {}".format(key, value))
        result.append("%s uses %s" % (key, value))
    return result

print(whatTechTheyUse(Google='Angular', Facebook='react', Microsoft='.NET'))

***的拆包操作

Unpacking operators are used to unpack the variables from iterable data types like lists, tuples, and dictionaries.
A single asterisk() is used on any iterable given by Python.
The double asterisk(
*) is used to iterate over dictionaries.

carCompany = ['Audi','BMW','Lamborghini']
print(*carCompany)

techStackOne = {"React": "Facebook", "Angular" : "Google", "dotNET" : "Microsoft"}
techStackTwo = {"dotNET" : "Microsoft1"}
mergedStack = {**techStackOne, **techStackTwo}
print(mergedStack)

2. property屬性用法

https://www.liaoxuefeng.com/wiki/1016959663602400/1017502538658208

在python中如果直接通過(guò)公有變量的方式把參數(shù)對(duì)外開(kāi)放塌西,則調(diào)用者可以隨便修改參數(shù)值。如果通過(guò)類似java的get,set方法,則又略顯復(fù)雜劈猪。在python中使用property可以兼容兩者的功能,讀取值的時(shí)候?qū)嶋H使用的是get方法混狠,賦值的時(shí)候調(diào)用的是set方法岸霹。

class Student(object):
    def get_score(self):
        return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError("score must be an integer!")
        if value < 0 or value > 100:
            raise ValueError("score must between 0 ~ 100!")
        self._score = value

    def del_score(self):
        del self._score

    score = property(get_score, set_score, del_score)

student = Student()
student.score = 99
print(student.score)
student.score = 102

可以使用裝飾器(java中為注解)簡(jiǎn)化

class Student(object):
    @property
    def score(self):
        return self._score

    # 這里的score要和帶有@property注解的方法名對(duì)應(yīng)
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError("score must be an integer!")
        if value < 0 or value > 100:
            raise ValueError("score must between 0 ~ 100!")
        self._score = value

    @score.deleter
    def del_score(self):
        del self._score

    # score = property(get_score, set_score, del_score)

student = Student()
student.score = 99
print(student.score)
student.score = 102

也可以通過(guò)下面的方式自定義(描述符)

class Name:
    def __get__(self, obj, cls=None):
        pwd = input('請(qǐng)輸入獲取密碼')
        if pwd == '123':
            return obj._name
        else:
            print('密碼不正確,獲取失敗')
    
    def __set__(self, obj, value):
        pwd = input('請(qǐng)輸入設(shè)置密碼')
        if pwd == '321':
            obj._name = value
            print('設(shè)置成功')
        else:
            print('密碼不正確将饺,設(shè)置失敗')

class Student:
    name = Name()

s = Student()
s.name = '小明'
print(s.name)

3. from __future__ import *的作用

https://blog.csdn.net/zzc15806/article/details/81133045

這樣的做法的作用就是將新版本的特性引進(jìn)當(dāng)前版本中贡避,也就是說(shuō)我們可以在當(dāng)前版本使用新版本的一些特性。主要是為了版本兼容性予弧,python中有個(gè)six庫(kù)是專門用來(lái)處理版本兼容問(wèn)題的刮吧。

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
#  兼容python2.x
print("hello world")
# 在python2.x版本中值為2,有了上面的導(dǎo)入之后掖蛤,值和python3.x版本一致都為2.5
print(5/2)

4. 魔法方法 :__getitem__ 杀捻、 __len__、__setitem__等的使用

http://www.reibang.com/p/cca8e8834066

在Python中蚓庭,如果我們想實(shí)現(xiàn)創(chuàng)建類似于序列和映射的類(可以迭代以及通過(guò)[下標(biāo)]返回元素)致讥,可以通過(guò)重寫魔法方法getitemsetitem器赞、delitem垢袱、len方法去模擬。當(dāng)然有很多其他魔法方法港柜,比如__cmp__(self, other),__add__(self, other),參考(https://pyzh.readthedocs.io/en/latest/python-magic-methods-guide.html):请契,其作用類似于C++的操作符重載。

魔術(shù)方法的作用:
getitem(self,key):返回鍵對(duì)應(yīng)的值夏醉。
setitem(self,key,value):設(shè)置給定鍵的值
delitem(self,key):刪除給定鍵對(duì)應(yīng)的元素爽锥。
len():返回元素的數(shù)量

import collections

Card = collections.namedtuple("Card", ["rank", "suit"])
# 也可以使用一個(gè)類來(lái)定義Card
# class Card:
#     def __init__(self,rank,suit):
#         self.rank = rank
#         self.suit = suit


class Puke:
    ranks = [str(n) for n in range(2, 11)] + list("JQKA")
    suits = "黑桃 方塊 梅花 紅心".split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, item):
        return self._cards[item]

    def __setitem__(self, key, value):
        print(key, value)
        self._cards[key] = value

pk = Puke()
print(len(pk))
print(pk[2:6])
print(pk[12::13])

5. 元類

https://www.geeksforgeeks.org/how-to-create-an-instance-of-a-metaclass-that-run-on-both-python2-and-python3/
https://www.zhihu.com/column/c_1604522311041966081
https://www.liaoxuefeng.com/discuss/969955749132672/1195234549018496

元類是用來(lái)動(dòng)態(tài)生產(chǎn)功能類的類,是類驗(yàn)證的高效工具畔柔,防止子類繼承某些類功能氯夷,動(dòng)態(tài)生成類。

from typing import Any


class NoInstance(type):
    # 類實(shí)例化
    def __call__(self, *args, **kwargs):
        if len(args) == 0 or args[0] != "factory":
            raise TypeError("Can't instantiate directly")
        # return super().__call__(*args, **kwargs)
        return super().__call__(*(), **kwargs)


class Last_of_us(metaclass= NoInstance):
    def play(self):
        print("the Last Of Us is really funny")


class Uncharted(metaclass= NoInstance):
    def play(self):
        print("the Uncharted is really funny")


class PSGame(metaclass= NoInstance):
    def play(self):
        print("PS has many games")


class GameFactory:
    games = {"last_of_us": Last_of_us, "uncharted": Uncharted}

    def __new__(cls, name):
        if name in cls.games:
            return cls.games[name]("factory")
        else:
            return PSGame()


uncharted = GameFactory("uncharted")
uncharted.play()
last_of_us = GameFactory("last_of_us")
last_of_us.play()
psgame = GameFactory("else")
psgame.play()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末靶擦,一起剝皮案震驚了整個(gè)濱河市肠槽,隨后出現(xiàn)的幾起案子擎淤,更是在濱河造成了極大的恐慌,老刑警劉巖秸仙,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嘴拢,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡寂纪,警方通過(guò)查閱死者的電腦和手機(jī)席吴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)捞蛋,“玉大人孝冒,你說(shuō)我怎么就攤上這事∧馍迹” “怎么了庄涡?”我有些...
    開(kāi)封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)搬设。 經(jīng)常有香客問(wèn)我穴店,道長(zhǎng),這世上最難降的妖魔是什么拿穴? 我笑而不...
    開(kāi)封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任泣洞,我火速辦了婚禮,結(jié)果婚禮上默色,老公的妹妹穿的比我還像新娘球凰。我一直安慰自己,他們只是感情好腿宰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布呕诉。 她就那樣靜靜地躺著,像睡著了一般吃度。 火紅的嫁衣襯著肌膚如雪甩挫。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天规肴,我揣著相機(jī)與錄音捶闸,去河邊找鬼夜畴。 笑死拖刃,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的贪绘。 我是一名探鬼主播兑牡,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼税灌!你這毒婦竟也來(lái)了均函?” 一聲冷哼從身側(cè)響起亿虽,我...
    開(kāi)封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎苞也,沒(méi)想到半個(gè)月后洛勉,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡如迟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年收毫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片殷勘。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡此再,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出玲销,到底是詐尸還是另有隱情输拇,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布贤斜,位于F島的核電站策吠,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蠢古。R本人自食惡果不足惜奴曙,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望草讶。 院中可真熱鬧洽糟,春花似錦、人聲如沸堕战。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)嘱丢。三九已至薪介,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間越驻,已是汗流浹背汁政。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留缀旁,地道東北人记劈。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像并巍,于是被迫代替她去往敵國(guó)和親目木。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容