程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python高級培訓-第二次任務

編輯:Python

動態給實例添加屬性和方法並使用

from types import MethodType #引入包 使類外部方法可以調用
#創建一個類
class Cat(object):
name = "Tom"
def __init__(self): #初始化
pass
c=Cat()
#動態添加屬性,體現了語言的的特點(靈活)
c.run = "貓在跑"
print(c.run)#打印顯示屬性
#動態的添加方法
def Run(self):
print(self.name+"在跑步")
#類似於偏函數
c.exercise = MethodType(Run,c) #為將Run方法傳值給c對象 並將其賦值給c.exercise屬性
c.exercise() #調用c.exercise屬性
#如果我們想要限制實例的屬性怎麼辦?
#比如:只允許給對象添加name、age、height、weight屬性
#解決:定義類的時候,定義一個特殊的屬性(__slots__),該屬性可以限制動態添加的屬性
#__slots__ = ("name","age","Run") 在括號裡的內容是可以添加的屬性

限制訪問對象及訪問方法 property的用法

property的用法詳見:Python property() 函數 | 菜鳥教程

property() 函數的作用是在新式類中返回屬性值。

語法

以下是 property() 方法的語法:

class property([fget[, fset[, fdel[, doc]]]])

參數

  • fget -- 獲取屬性值的函數
  • fset -- 設置屬性值的函數
  • fdel -- 刪除屬性值函數
  • doc -- 屬性描述信息

返回值

返回新式類屬性。

class Person(object):
def __init__(self,age):
#1屬性直接對外暴露
#1self.age=age
#限制訪問
self.__age=age
#2通過get,set方法訪問age
def getAge(self):
return self.__age
def setAge(self, age):
if age < 0:
age = 0
self.__age = age
#3想要用點的形式去訪問 受限制對象的方法
#方法名為受限制的變量去掉雙下劃綫
#property 可以讓你對受限制訪問的屬性使用點語法
@property
def age(self):
return self.__age
@age.setter #去掉下劃線的方法名字.setter
def age(self,age):
if age < 0:
age = 0
self.__age = age
per = Person(18)
#1屬性直接對外暴露
#不安全,且沒事數據過濾
per.age=-10
print(per.age)
#2使用限制訪問,需要自己寫set和get方法才能訪問
per.setAge(15)
print(per.getAge())
#3想要用點的形式去訪問 受限制對象
per.age=100 #相當於調用setAge
print(per.age) #相當於調用getAge

運算符重載

 運算符重載:
        什麼是運算符重載
            讓自定義的類生成的對象(實例)能夠使用運算符進行操作
        作用:
            讓自定義的實例像內建對象一樣進行運算符操作
            讓程序簡潔易讀
            對自定義對象將運算符賦予新的規則

詳細看:python之運算符重載_python -學習筆記-CSDN博客_python運算符重載

#不同的類型用加法會有不同的解釋
print(1+2)
print("1"+"2")
class Person(object):
def __init__(self,num):
self.num = num
#運算符重載
#self代表“+”前邊的對象(per1) other代表“+”後邊的對象(per2)
def __add__(self, other):
return Person(self.num + other.num)
def __str__(self):
return "num = " + str(self.num) #self.num為數字型 str()轉換成字符串
per1=Person(1)
per2=Person(2)
print(per1+per2) #per1+per2 === per1.__add__(per2)
print(per1.__add__(per2))
# 創建一個類
class Grade(object):
def __init__(self, num): #初始化
self.num = num
# 運算符重載
# self代表想要運算的數字 other代表次冪
def __pow__(self, other):
return self.num ** other.num
def __str__(self):
return "num = " + str(self.num) # self.num為數字型 str()轉換成字符串
# #判斷gra1的值是否<gra2
def __lt__(self, other):
return self.num < other.num
# #判斷gra1的值是否<=gra2
def __le__(self, other):
return self.num <= other.num
# #判斷gra1的值是否==gra2
def __eq__(self, other):
return self.num == other.num
# #判斷gra1的值是否!=gra2
def __ne__(self, other):
return self.num != other.num
# #判斷gra1的值是否>gra2
def __gt__(self, other):
return self.num > other.num
# #判斷gra1的值是否>=gra2
def __ge__(self, other):
return self.num >= other.num
grade1 = Grade(3) #實例化對象 並賦值給grade1
grade2 = Grade(4) #實例化對象 並賦值給grade2
grade3 = Grade(2) #實例化對象 並賦值給grade3
gra1=grade1.__pow__(grade3) #將grade1平方之後的數字賦值給gra1
gra2=grade2.__pow__(grade3) #將grade2平方之後的數字賦值給gra2
print("grade1的平方為 "+ str(grade1.__pow__(grade3))) #輸出grade1平方之後的數字
print("grade2的平方為 "+ str(grade2.__pow__(grade3))) #輸出grade2平方之後的數字
print("gra1的值是否<gra2 "+str(gra1.__lt__(gra2))) #判斷gra1的值是否<gra2
print("gra1的值是否<=gra2 "+str(gra1.__le__(gra2))) #判斷gra1的值是否<=gra2
print("gra1的值是否==gra2 "+str(gra1.__eq__(gra2))) #判斷gra1的值是否==gra2
print("gra1的值是否!=gra2 "+str(gra1.__ne__(gra2))) #判斷gra1的值是否!=gra2
print("gra1的值是否>gra2 "+str(gra1.__gt__(gra2))) #判斷gra1的值是否>gra2
print("gra1的值是否>=gra2 "+str(gra1.__ge__(gra2))) #判斷gra1的值是否>=gra2

Python3 操作符重載方法

原文: Python3 操作符重載方法_Luzhuo 的博客-CSDN博客_python3 重載運算符

#coding=utf-8
# specialfuns.py 操作符重載方法
# 類(class)通過使用特殊名稱的方法(__len__(self))來實現被特殊語法(len())的調用
# 構造 與 析構 方法
class demo1:
# 構造方法, 對象實例化時調用
def __init__(self):
print("構造方法")
# 析構方法, 對象被回收時調用
def __del__(self):
print("析構方法")
# new
class demo2(object):
# __init__之前調用, 一般用於重寫父類的__new__方法, 具體使用見 類 文章的 元類 代碼部分(http://blog.csdn.net/rozol/article/details/69317339)
def __new__(cls):
print("new")
return object.__new__(cls)
# 算術運算
class demo3:
def __init__(self, num):
self.data = num
# +
def __add__(self, other):
return self.data + other.data
# -
def __sub__(self, other):
return self.data - other.data
# *
def __mul__(self, other):
return self.data * other.data
# /
def __truediv__(self, other):
return self.data / other.data
# //
def __floordiv__(self, other):
return self.data // other.data
# %
def __mod__(self, other):
return self.data % other.data
# divmod()
def __divmod__(self, other):
# 商(10/5),余數(10%5)
return self.data / other.data, self.data % other.data
# **
def __pow__(self, other):
return self.data ** other.data
# <<
def __lshift__(self, other):
return self.data << other.data
# >>
def __rshift__(self, other):
return self.data >> other.data
# &
def __and__(self, other):
return self.data & other.data
# ^
def __xor__(self, other):
return self.data ^ other.data
# |
def __or__(self, other):
return self.data | other.data
class none:
def __init__(self, num):
self.data = num
# 反算術運算符(a+b, 若a不支持算術運算符,則尋找b的算術運算符)(注:位置變換, 在原始函數名前+r)
class demo4:
def __init__(self, num):
self.data = num
# +
def __radd__(self, other):
return other.data + self.data
# -
def __rsub__(self, other):
return other.data - self.data
# *
def __rmul__(self, other):
return other.data * self.data
# /
def __rtruediv__(self, other):
return other.data / self.data
# //
def __rfloordiv__(self, other):
return other.data // self.data
# %
def __rmod__(self, other):
return other.data % self.data
# divmod()
def __rdivmod__(self, other):
return other.data / self.data, other.data % self.data
# **
def __rpow__(self, other):
return other.data ** self.data
# <<
def __rlshift__(self, other):
return other.data << self.data
# >>
def __rrshift__(self, other):
return other.data >> self.data
# &
def __rand__(self, other):
return other.data & self.data
# ^
def __rxor__(self, other):
return other.data ^ self.data
# |
def __ror__(self, other):
return other.data | self.data
# 增量賦值運算,(注:位置同原始函數,在原始函數名前+i)
class demo5():
def __init__(self, num):
self.data = num
# +=
def __iadd__(self, other):
return self.data + other
# -=
def __isub__(self, other):
return self.data - other
# *=
def __imul__(self, other):
return self.data * other
# /=
def __itruediv__(self, other):
return self.data / other
# //=
def __ifloordiv__(self, other):
return self.data // other
# %=
def __imod__(self, other):
return self.data % other
# **=
def __ipow__(self, other):
return self.data ** other
# <<=
def __ilshift__(self, other):
return self.data << other
# >>=
def __irshift__(self, other):
return self.data >> other
# &=
def __iand__(self, other):
return self.data & other
# ^=
def __ixor__(self, other):
return self.data ^ other
# |=
def __ior__(self, other):
return self.data | other
# 比較運算符
class demo6:
def __init__(self, num):
self.data = num
# <
def __lt__(self, other):
return self.data < other.data
# <=
def __le__(self, other):
return self.data <= other.data
# ==
def __eq__(self, other):
return self.data == other.data
# !=
def __ne__(self, other):
return self.data != other.data
# >
def __gt__(self, other):
return self.data > other.data
# >=
def __ge__(self, other):
return self.data >= other.data
# 一元操作符
class demo7:
def __init__(self, num):
self.data = num
# + 正號
def __pos__(self):
return +abs(self.data)
# - 負號
def __neg__(self):
return -abs(self.data)
# abs() 絕對值
def __abs__(self):
return abs(self.data)
# ~ 按位取反
def __invert__(self):
return ~self.data
# complex() 字符轉數字
def __complex__(self):
return 1+2j
# int() 轉為整數
def __int__(self):
return 123
# float() 轉為浮點數
def __float__(self):
return 1.23
# round() 近似值
def __round__(self):
return 1.123
# 格式化
class demo8:
# print() 打印
def __str__(self):
return "This is the demo."
# repr() 對象字符串表示
def __repr__(self):
return "This is a demo."
# bytes() 對象字節字符串表現形式
def __bytes__(self):
return b"This is one demo."
# format() 格式化
def __format__(self, format_spec):
return self.__str__()
# 屬性訪問
class demo9:
# 獲取(不存在)屬性
def __getattr__(self):
print ("訪問的屬性不存在")
# getattr() hasattr() 獲取屬性
def __getattribute__(self, attr):
print ("訪問的屬性是%s"%attr)
return attr
# setattr() 設置屬性
def __setattr__(self, attr, value):
print ("設置 %s 屬性值為 %s"%(attr, value))
# delattr() 刪除屬性
def __delattr__(self, attr):
print ("刪除 %s 屬性"%attr)
# ===================================================================
# 描述器(類(test1)的實例出現在屬主類(runtest)中,這些方法才會調用)(注:函數調用,這些方法不會被調用)
class test1:
def __init__(self, value = 1):
self.value = value * 2
def __set__(self, instance, value):
print("set %s %s %s"%(self, instance, value))
self.value = value * 2
def __get__(self, instance, owner):
print("get %s %s %s"%(self, instance, owner))
return self.value
def __delete__(self, instance):
print("delete %s %s"%(self, instance))
del self.value
class test2:
def __init__(self, value = 1):
self.value = value + 0.3
def __set__(self, instance, value):
print("set %s %s %s"%(self, instance, value))
instance.t1 = value + 0.3
def __get__(self, instance, owner):
print("get %s %s %s"%(self, instance, owner))
return instance.t1
def __delete__(self, instance):
print("delete %s %s"%(self, instance))
del self.value
class runtest:
t1 = test1()
t2 = test2()
# ---
# 自定義property
class property_my:
def __init__(self, fget=None, fset=None, fdel=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
# 對象被獲取(self自身, instance調用該對象的對象(demo9), owner調用該對象的對象類對象(demo9))
def __get__(self, instance, owner):
print("get %s %s %s"%(self, instance, owner))
return self.fget(instance)
# 對象被設置屬性時
def __set__(self, instance, value):
print("set %s %s %s"%(self, instance, value))
self.fset(instance, value)
# 對象被刪除時
def __delete__(self, instance):
print("delete %s %s"%(self, instance))
self.fdel(instance)
class demo10:
def __init__(self):
self.num = None
def setvalue(self, value):
self.num = value
def getvalue(self):
return self.num
def delete(self):
del self.num
x = property_my(getvalue, setvalue, delete)
# ===================================================================
# 自定義容器
class lis:
def __init__(self, *args):
self.lists = args
self.size = len(args)
self.startindex = 0
self.endindex = self.size
# len() 容器元素數量
def __len__(self):
return self.size;
# lis[1] 獲取元素
def __getitem__(self, key = 0):
return self.lists[key]
# lis[1] = value 設置元素
def __setitem__(self, key, value):
pass
# del lis[1] 刪除元素
def __delitem__(self, key):
pass
# 返回迭代器
def __iter__(self):
return self
# rversed() 反向迭代器
def __reversed__(self):
while self.endindex > 0:
self.endindex -= 1
yield self[self.endindex]
# next() 迭代器下個元素
def __next__(self):
if self.startindex >= self.size:
raise StopIteration # 控制迭代器結束
elem = self.lists[self.startindex]
self.startindex += 1
return elem
# in / not in
def __contains__(self, item):
for i in self.lists:
if i == item:
return True
return False
# yield 生成器(執行一次返回,下次繼續執行後續代碼返回)
def yielddemo():
num = 0
while 1: # 1 == True; 0 == False
if num >= 10:
raise StopIteration
num += 1
yield num
# 能接收數據的生成器
def yielddemo_1():
while 1:
num = yield
print(num)
# with 自動上下文管理
class withdemo:
def __init__(self, value):
self.value = value
# 返回值為 as 之後的值
def __enter__(self):
return self.value
# 執行完成,退出時的數據清理動作
def __exit__(self, exc_type, exc_value, traceback):
del self.value
if __name__ == "__main__":
# 構造與析構
d1 = demo1()
del d1
# new
d2 = demo2()
# 算術運算符
d3 = demo3(3)
d3_1 = demo3(5)
print(d3 + d3_1)
print(d3 - d3_1)
print(d3 * d3_1)
print(d3 / d3_1)
print(d3 // d3_1)
print(d3 % d3_1)
print(divmod(d3, d3_1))
print(d3 ** d3_1)
print(d3 << d3_1)
print(d3 >> d3_1)
print(d3 & d3_1)
print(d3 ^ d3_1)
print(d3 | d3_1)
# 反運算符
d4 = none(3)
d4_1 = demo4(5)
print(d4 + d4_1)
print(d4 - d4_1)
print(d4 * d4_1)
print(d4 / d4_1)
print(d4 // d4_1)
print(d4 % d4_1)
print(divmod(d4, d4_1))
print(d4 ** d4_1)
print(d4 << d4_1)
print(d4 >> d4_1)
print(d4 & d4_1)
print(d4 ^ d4_1)
print(d4 | d4_1)
# 增量賦值運算(測試時注釋其他代碼)
d5 = demo5(3)
d5 <<= 5
d5 >>= 5
d5 &= 5
d5 ^= 5
d5 |= 5
d5 += 5
d5 -= 5
d5 *= 5
d5 /= 5
d5 //= 5
d5 %= 5
d5 **= 5
print(d5)
# 比較運算符
d6 = demo6(3)
d6_1 = demo6(5)
print(d6 < d6_1)
print(d6 <= d6_1)
print(d6 == d6_1)
print(d6 != d6_1)
print(d6 > d6_1)
print(d6 >= d6_1)
# 一元操作符(測試時注釋其他代碼)
d7 = demo7(-5)
num = +d7
num = -d7
num = abs(d7)
num = ~d7
print(num)
print(complex(d7))
print(int(d7))
print(float(d7))
print(round(d7))
# 格式化
d8 = demo8()
print(d8)
print(repr(d8))
print(bytes(d8))
print(format(d8, ""))
# 屬性訪問
d9 = demo9()
setattr(d9, "a", 1) # => 設置 a 屬性值為 1
print(getattr(d9, "a")) # => a / 訪問的屬性是a
print(hasattr(d9, "a")) # => True / 訪問的屬性是a
delattr(d9, "a") # 刪除 a 屬性
# ---
d9.x = 100 # => 設置 x 屬性值為 100
print(d9.x) # => x / 訪問的屬性是x
del d9.x # => 刪除 x 屬性
# 描述器
r = runtest()
r.t1 = 100 # => <__main__.test1> <__main__.runtest> 100
print(r.t1) # => 200 / <__main__.test1> <__main__.runtest> <class '__main__.runtest'>
del r.t1 # => <__main__.test1> <__main__.runtest>
r.t2 = 200 # => <__main__.test2> <__main__.runtest> 200 / <__main__.test1> <__main__.runtest> 200.3
print(r.t2) # => 400.6 / <__main__.test2> <__main__.runtest> <class '__main__.runtest'> / <__main__.test1> <__main__.runtest> <class '__main__.runtest'>
del r.t2 # <__main__.test2> <__main__.runtest>
# ---
# 自定義property
d10 = demo10()
d10.x = 100; # => <__main__.property_my> <__main__.demo10> 100
print(d10.x) # => 100 / <__main__.property_my> <__main__.demo10> <class '__main__.demo10'>
del d10.x # => <__main__.property_my> <__main__.demo10>
d10.num = 200;
print(d10.num) # => 200
del d10.num
# 自定義容器(迭代器Iterator)
lis = lis(1,2,3,4,5,6)
print(len(lis))
print(lis[1])
print(next(lis))
print(next(lis))
print(next(lis))
for i in lis:
print (i)
for i in reversed(lis):
print (i)
print(3 in lis)
print(7 in lis)
print(3 not in lis)
print(7 not in lis)
# yield 生成器(可迭代對象Iterable)
for i in yielddemo():
print (i)
# ---
iters = iter(yielddemo())
print(next(iters))
print(next(iters))
# --- 發送數據給生成器 ---
iters = yielddemo_1()
next(iters)
iters.send(6) # 發送數據並執行
iters.send(10)
# with 自動上下文管理
with withdemo("Less is more!") as s:
print(s)

 還可以參考:operator --- 標准運算符替代函數 — Python 3.10.1 文檔


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved