Python動態生成方法

2022-06-27 21:09:08 字數 2768 閱讀 9065

背景:想要通過讀取配置檔案動態生成方法

實踐1使用關鍵字exec實現生成方法,參考

m = """

def fn(a,b):

c=2s=a+b+c

return s

"""exec(m)

print(fn(3, 6))

執行結果:

11
實踐2直接給類和方法繫結自定義方法 a.fun=fun

class a():

dd = 37

def __init__(self, de):

self.de = de

print(globals())

m = """

def fn(a,b):

c=2s=a+b+c

return s

"""exec(m)

print(globals())

if __name__ == '__main__':

c = 17

a = a(35)

print('\n\n\n')

print(a.__dict__)

print(a.__dict__)

執行結果:

可以看到方法的確已經生成了,但是此時無論是類a還是例項a都沒有這個方法。下面給這個類加上此方法:

class a():

dd = 37

def __init__(self, de):

self.de = de

m = """

def fn(a,b):

c=2s=a+b+c

return s

"""exec(m)

a.fn = fn # 這裡需要注意的是,fn函式會被當做 staticmethod,所以是不能被例項呼叫的

if __name__ == '__main__':

c = 17

a = a(35)

print(a.__dict__)

print(a.fn(5, 6))

print(a.__dict__)

# print(a.fn(5, 6)) # 報錯 typeerror: fn() takes 2 positional arguments but 3 were given 因為例項呼叫多傳了self

執行結果:

優化實踐2

使用types給類新增方法,參考

import types

class a():

dd = 37

def __init__(self, de):

self.de = de

def ss(self, a):

self.de = self.de + a

m = """

def fn(a,b):

c=2s=b+c

return s

"""exec(m)

a.f = types.methodtype(fn, a) # 這裡fn函式會被當做類方法,第乙個引數a,會被當作self傳入,所以類和例項都能呼叫此方法

if __name__ == '__main__':

c = 17

a = a(35)

print(a.__dict__)

print(a.f(6))

print(a.__dict__)

print(a.f(3))

執行結果:

可以看到無論是例項還是類,均能夠使用自定義的方法

這裡補充下,如果只想給例項新增私有自定義方法,可以 a.fun=types.methodtype(fn, a)

import types

class a():

dd = 37

def __init__(self, de):

self.de = de

def ss(self, a):

self.de = self.de + a

m = """

def fn(a,b):

c=2s=b+c

return s

"""exec(m)

if __name__ == '__main__':

c = 17

a = a(35)

a.f = types.methodtype(fn, a)

print(a.__dict__)

# print(a.f(6)) # attributeerror: type object 'a' has no attribute 'f' 例項的私有方法,類無法呼叫

print(a.__dict__)

print(a.f(3))

執行結果: 例項的私有方法,類無法呼叫

Python隨機數生成方法

1.random.seed int 1 2 3 4 5 6 7 8 9 10 random.seed 10 printrandom.random 0.57140259469 random.seed 10 printrandom.random 0.57140259469 同乙個種子值,產生的隨機數相同...

Python隨機數生成方法

假設你對在python生成隨機數與random模組中最經常使用的幾個函式的關係與不懂之處。以下的文章就是對python生成隨機數與random模組中最經常使用的幾個函式的關係,希望你會有所收穫,以下就是這篇文章的介紹。random.random 用於生成 用於生成乙個指定範圍內的隨機符點數,兩個引數...

Python隨機數生成方法

假設你對在python生成隨機數與random模組中最經常使用的幾個函式的關係與不懂之處。以下的文章就是對python生成隨機數與random模組中最經常使用的幾個函式的關係,希望你會有所收穫,以下就是這篇文章的介紹。random.random 用於生成 用於生成乙個指定範圍內的隨機符點數,兩個引數...