Python運算子過載

2021-06-28 21:00:31 字數 3994 閱讀 1363

print('呼叫父類建構函式')

def parentmethod(self):

print('呼叫父類方法')

def setattr(self, attr):

self.parentattr = attr

def getattr(self):

print('父類屬性:', self.parentattr)

def __del__(self):

print('父類析構')

class child(parent):

def __init__(self):

print('呼叫子類建構函式')

def childmethod(self):

print('呼叫子類方法 child method')

def __del__(self):

print('子類析構')

def __str__(self):

return 'class name:child'

def __repr__(self):

return 'classname:child'

c = child()

c.childmethod()

c.parentmethod()

c.setattr(200)

c.getattr()

if isinstance( c, parent ):

print('yes')

if issubclass( child, parent ):

print('yes')

#del c

print(repr(c)) #輸出classname:child,repr(c)會呼叫c.__repr__(self)

print(str(c)) #輸出class name:child,str(c)會呼叫c.__str__(self)

參考:

7.1    減法過載

class number:

def __init__(self, start):

self.data = start

def __sub__(self, other): #minus method

return number(self.data - other)

def show(self):

print(self.data)

number = number(20)

y = number - 10 # invoke __sub__ method

y.show() #輸出10

7.2 迭代過載

class indexer:

def __getitem__(self, index): #iter override

return index ** 2

x = indexer()

x[2]

for i in range(5):

print (x[i]) #x[i]呼叫x.__getitem__(i)

7.3 索引過載

class stepper:

def __getitem__(self, i):

return self.data[i]

x = stepper()

x.data = 'spam'

x[1] #call __getitem__

for item in x: #call __getitem__

print (item)

'''輸出:sp

am'''7.4 getattr/setattr過載

class empty:

def __getattr__(self,attrname):

if attrname == 'age':

return 40

else:

raise (attributeerror,attrname )

x = empty()

print (x.age) #call __getattr__

class accesscontrol:

def __setattr__(self, attr, value):

if attr == 'age':

# self.attrname = value loops!

self.__dict__[attr] = value

else:

print (attr)

raise (attributeerror, attr + 'not allowed' )

x = accesscontrol()

x.age = 40 #call __setattr__

print(x.__dict__)

x.name = 'wang' #raise exception

7.5 列印過載

class adder:

def __init__(self, value=0):

self.data = value

def __add__(self, other):

self.data += other

class addrepr(adder):

def __repr__(self):

return 'addrepr(%s)' % self.data

x = addrepr(2) #run __init__

x + 1 #run __add__

print (x) #run __repr__ 輸出addrepr(3)

7.6 call呼叫函式過載

class prod:

def __init__(self, value):

self.value = value

def __call__(self, other):

return self.value * other

p = prod(2) #call __init__

print (p(1)) #call __call__ 輸出2

print (p(2)) #輸出4

7.7 析構函式過載

class life:

def __init__(self, name='name'):

print ( 'hello', name )

self.name = name

def __del__(self):

print ( 'goodby', self.name )

brain = life('brain') #call __init__,輸出hello brain

brain = 'loretta' # call __del__ ,輸出goodby brain,brain指向了別的物件,原來的類物件要釋放,

故呼叫析構函式

7.8 加法函式過載

class test(object):

def __init__(self, value):

self.value = value

def __add__(self, x):

return self.value + x.value

a = test(3)

b = test(4)

print (a + b)

ref:

Python 運算子過載

在 python 中is 是兩個運算子,對物件進行比較,分別對id,type value 進行比較。is 比較id type value三維 而 僅 比較value。實驗發現其實is,僅僅是比較一些簡單的基礎變數。class test object def init self self.value ...

python 運算子過載

運算子過載就是讓用類寫成的物件,可截獲並響應用在內建型別上的運算 加法,切片,列印和點號運算等 1.以雙下劃線命名的方法 x 的特殊鉤子,python運算子過載的實現是提供特殊命名的方法來攔截運算,python替每種運算和特殊命名的方法之間,定義了固定不變的對映關係 2.當例項出現在內建運算時,這類...

python運算子過載

python的運算子過載可以算是語言的一大特色了。相比c python進行運算子過載將會方便許多,只需要重寫以 開頭和結尾的特殊方法即可,下面看乙個簡單的例子 迭代器 class indexer object value 1 加法運算過載 def add self,value return self...