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ò)重寫魔法方法getitem、setitem器赞、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()