參考鏈接: Python中的Inplace與標準運算符
點擊上方“藍字”關注我們
?作者 | 孔令昌
?編輯 | 張嬋
python怎么給字母賦值。?對于 asterisk符號的使用,本文分為預定義(predefined)和自定義(customized)兩部分進行介紹。
?預定義部分,是指 Python 語言中已經預先定義好的部分,直接用就可以了;
?自定義,是指定制的,需要程序員自定義相應的功能。
?注意,這里討論的 asterisk 符號的使用包括*? 符號和**? 符號兩種類型。
?預定義
python可以用什么符號給變量賦值,?下面介紹 asterisk 符號在數值類型、非數值內置類型、函數定義和賦值中的用法。
?1
?數值類型中 asterisk 符號的用法
?在整型和浮點型等數值類型中,*? 符號作為乘法運算符,**? 符號作為乘方運算符。具體的示例程序,如下:
?x,y=2,4
python的符號??res1=x*y# 8
?res2=x**y# 16
?res1*=x# 16
?res2**=x# 256
?2
在Python中、?非數值內置類型中 asterisk 符號用法
?所有的非數值內置類型都不支持**? 符號;而對于*? 符號,只有? tuple 或 list 類型支持*符號操作符,而 set 或 dict 類型不支持,具體如下:
?元組(tuple)或列表(list)類型,*? 符號可使非數值類型變量重復指定次數;
?而集合(set)和字典類型(dict)是不支持*? 符號操作符的,會拋出"TypeError: unsupportedoperand type(s)"? 異常。具體示例如下:
?# list examples print([] * 3) # [] print(list() * 3) # []
可以用else作為變量名、?print([0]*3)# [0, 0, 0]
?# tuple examples print(() * 3) # ()
?print(tuple()*3)# ()
?print((0,)*3)# (0, 0, 0)
?# set examples, throw TypeError Exception try:
python的變量。?set()*3set([])*3{0}*3
?exceptTypeErrorase:
?print(e)
?pass
?# dict examples, throw TypeError Exception
python中elif??try:
?{}*3dict()*3{0:'0'}*3
?exceptTypeErrorase:
?print(e)
?pass
Python賦值,?注意,(0,)? 是元組類型,而(0)是整型,不是元組類型,區別只在于缺少了一個逗號(,)。
?3
?asterisk 符號在函數定義中的用法
?在 Python 函數定義中,*? 符號表示允許函數接受數量可變的參數(arguments);**? 符號表示允許函數接受數量可變的關鍵字參數(keyword arguments)。具體示例如下:
?deffunc(*args,**kwargs):print('args:',args)print('kwargs:',kwargs)
python變量賦值規范,?func((0,1,2),3,4,5,key=0,value='0')# args: ((0, 1, 2), 3, 4, 5)
?# kwargs: {'key': 0, 'value': '0'}
?注意,在 Python 函數定義中,帶有*? 符號參數,必須在帶有**? 符號參數之前。
?在 Python 3 中,有一個新用法,稱為 bare asterisk/star。即,在函數定義中,參數之間,有一個光禿禿的*? 符號。這種用法的含義是 barestar 的后面,只能接受關鍵字參數。更多解釋參見 PEP3102--Keyword-OnlyArguments (https://www.python.org/dev/peps/pep-3102/)具體示例如下:
?defcompare1(x,y,*,key=None):
python運算符,?print('x:',x)print('y:',y)print('key:',key)returnx>y
?defcompare2(x,y,*,z,key=None):
?print('x:',x)print('y:',y)print('key:',key)ifz<0:z*=-1
?returnzifx>yelse-1
?compare1(3,5)compare2(3,5,key=2,z=2)try:
python賦值符號,?compare2(3,5,2)
?exceptTypeErrorase:
?print(e)
?4
?asterisk 符號在賦值中的用法
python變量名中不能出現的符號。?在調用函數時,采用*? 符號可以拆解一些內置類型,使之變成一個個單獨的元素再傳入函數中。具體示例如下:
?deffunc(*args):
?print('args:',args)
?params=['RGBA',(1,2,3),[1,2,3],{1,2,3}]
?# call function with arguments(* included) print("\ncall function with arguments(* included)") for args in params:
python怎么賦值、?func(*args)
?# call function with arguments(* not included) print("\ncall function with arguments(* not included)") for args in params:
?func(args)
?在 Python3 中,還可以把帶有*? 符號的操作數(operand),或者說是變量,放到賦值符號的左側,從而擴展了迭代器(iterator)的拆解賦值。具體示例如下:
?iterators=[(0,1,2,3,4),'ABCDE',[0,1,2,3,4],{0,1,2,3,4}]foriteminiterators:
python變量類型有哪些、?x,*y,z=itemprint('\nitem:',item)
?print('x: %s, y: %s, z: %s'%(x,y,z))print('-'*50)
?自定義
?對于自定義的類,可以通過定義相應的魔法方法(magic method),實現 asterisk 符號運算符(operator)。asterisk 符號相關的操作符與魔法方法的具體對應關系,如表 1 所示。
?表1.asterisk 符號操作符與 magic 方法對應關系表
?操作符
?魔法方法
?原始的表現形式
?解釋
?*
?__mul__(self,other)
?self*other
?前向(forward)相乘方法
?*
?__rmul__(self,other)
?other*self
?反轉(reverse)相乘方法
?*=
?__imul__(self,other)
?self*=other
?原地(in-place)相乘方法
?**
?__pow__(self,other[,modulo])
?self**other
?前向乘方方法
?**
?__rpow__(self,other[,modulo])
?other**self
?反轉乘方方法
?**=
?__ipow__(self,other[,modulo])
?self**=other
?原地乘方方法
?注,反轉相乘方法和反轉乘方方法只有在 self 實例沒有定義對應的前向方法時調用;modulo 為可選參數,表示對 modulo 參數取模。
?下面定義了一個 Length 類,實現將長度的單位都轉換為米(meter)后,再進行相乘或乘方運算。具體示例代碼,如下:
?classLength(object):
?__metric={"mm":0.001,"cm":0.01,"m":1,"km":1000,"in":0.0254,"ft":0.3048,"yd":0.9144,"mi":1609.344}
?def__init__(self,value,unit="m"):
?self.value=valueself.unit=unit
?defconvert2meters(self):
?returnself.value*Length.__metric[self.unit]
?def__str__(self):
?"""Informal string representation for a user"""returnstr(self.convert2meters())
?def__repr__(self):
?"""Official/Formal string representation for a programmer"""return"Length("+str(self.value)+", '"+self.unit+"')"
?def__add__(self,other):
?meters=self.convert2meters()+other.convert2meters()returnLength(meters/Length.__metric[self.unit],self.unit)
?def__mul__(self,other):
?"""Regard the other object as a multiplier upon self"""meters=self.convert2meters()*other.convert2meters()returnLength(meters/Length.__metric[self.unit],self.unit)
?def__imul__(self,other):
?"""In-place multiplication"""
?meters=self.convert2meters()*other.convert2meters()self.value=meters/Length.__metric[self.unit]
?returnself
?def__pow__(self,other):
?"""Regard the other object as an exponent upon self"""meters=self.convert2meters()**other.convert2meters()returnLength(meters/Length.__metric[self.unit],self.unit)
?def__ipow__(self,other):
?"""In-place power"""
?meters=self.convert2meters()**other.convert2meters()self.value=meters/Length.__metric[self.unit]
?returnself
?if__name__=='__main__':x=Length(4)
?print(x)
?y=eval(repr(x))
?# Test * symbol operator
?z1=Length(4.5,"yd")*Length(1)
?z1*=xprint(repr(z1))print(z1)
?# Test ** operator
?z2=y**x
?z2**=Length(1)print(repr(z2))print(z2)
?參考資料
?[1]NumericTypeSpecialMethodsinChapter24.CreatingorExtendingDataTypes. https://www.linuxtopia.org/online_books/programming_books/python_programming/python_c h24s04.html
?[2] Magic Methods and OperatorOverloading. https://www.python-course.eu/python3_magic_methods.php
??
??
?
?
?覺得不錯,點個在看
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
同时也捎带提醒一句,如果你发现你 hook 系统的方法不起作用的时候,或许可以检查一下你项目里引入的第三方框架里是否也 hook 了和你一样的" alt="从使用 KVO 监听 readonly 属性说起">
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态