• No results found

Основи метапрограмування мовою Python

N/A
N/A
Protected

Academic year: 2021

Share "Основи метапрограмування мовою Python"

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

Дмитро Терлецький

Київський нацiональний унiверситет iменi Тараса Шевченка Факультет комп’ютерних наук та кiбернетики Кафедра iнтелектуальних програмних систем Спецiальнiсть: 121 Iнженерiя програмного забезпечення

Освiтня програма: Програмна iнженерiя 2020-2021

(2)

c

Д.О. Терлецький, 2020.

c

(3)

1

Однорiдна генерацiя.

2

Неоднорiдна генерацiя.

(4)
(5)

продукування програмами частин власного програмного

коду та (або) програмного коду iнших програм.

Однорiдна генерацiя програмних кодiв

– це динамiчне

продукування програмами частин власного програмного

коду та (або) програмного коду iнших програм з

використанням однiєї мови.

Триповi приклади:

Генерацiя програмних конструкцiй на певнiй мовi

програмування з використанням цiєї ж мови.

(6)

1 #---collection_meta_generator.py---2 import os

3

4 def collections_metegenerator(gen_name, seq_type,

5 deepness=1, with_map=None):

6 if not os.path.exists(’meta_gens’):

7 os.makedirs(’meta_gens’)

8 try:

9 file = open(r’./meta_gens/’ + gen_name + r’.py’, ’x’)

10 file.write(’\n’)

11 file.write(’def ’ + gen_name + ’(*args, gen_exp, ’

12 ’gen_exp_cond):\n’)

13 file.write(’ for i in args:\n’)

14 file.write(’ if not isinstance(i, ’ + seq_type + ’) ’

15 ’and not isinstance(i, str) and not ’

16 ’isinstance(i, int) and not ’

(7)

19 file.write(’ return "’ + gen_name + ’: One or all ’

20 ’received args have type different from ’

21 ’string, integer, float and ’ + seq_type

22 + ’."\n’)

23 file.write(’ gen_exp += " "\n’)

24 file.write(’ gen_exp_cond = "if " + gen_exp_cond\n’)

25 file.write(’\n’)

26 file.write(’ def iter_gen(args):\n’)

27 file.write(’ iter_exp = ""\n’)

28 file.write(’ for i in range(len(args)):\n’)

29 file.write(’ iter_exp += "for x" + str(i) + " in " + ’

30 ’str(args[i]) + " "\n’)

31 file.write(’ return iter_exp\n’)

32 file.write(’\n’)

33 if seq_type == ’list’:

34 file.write(’ g_exp = "[" + gen_exp + iter_gen(args) ’

(8)

36 elif seq_type == ’tuple’:

37 file.write(’ g_exp = "tuple(" + gen_exp + ’

38 ’iter_gen(args) + gen_exp_cond + ")"\n’)

39 elif seq_type == ’set’:

40 file.write(’ g_exp = "set(" + gen_exp + ’

41 ’iter_gen(args) + gen_exp_cond + ")"\n’)

42 elif seq_type == ’dict’:

43 file.write(’ g_exp = "dict(" + gen_exp + ’

44 ’iter_gen(args) + gen_exp_cond + ")"\n’)

45 file.write(’\n’)

46 file.write(’ return eval(g_exp)’)

47 file.write(’\n’)

48 file.close()

49 file = open(r’main.py’, ’r+’)

50 lines = file.readlines()

51 lines.insert(1, ’from meta_gens.’ + gen_name +

(9)

53 file.seek(0)

54 for line in lines:

55 file.write(line)

56 file.close()

57 except FileExistsError:

58 print(’Module with name ’ + gen_name +

59 ’.py already exists. Please change the name ’

60 ’of your future generator.’)

1 #---main.py---2

3 from collections_meta_generator import collections_metegenerator

4

5 a = (1, 3, ’a’, ’b’, 4.7)

6 b = (3, 5, ’aa’, 5.6)

(10)

8 d = {’bbb’, 6.3, 4.4}

9 f = {’a’: 1, ’b’: 2, ’c’: 3}

10 e = {’a’: ’asdd’, ’bdd’: 2, ’112jh’: 3.3}

11

12 collections_metegenerator(’my_1_gen’, ’tuple’)

13 # Result: creation of generators.my_1_gen.py 14

15 # Note! Run after generation.

16 print(my_1_gen(a, b, gen_exp=’(x0 + x1) * 2’,

17 gen_exp_cond=’x0.__class__ == x1.__class__’))

18

19 # Result: Module with name my_1_gen.py already exists. 20 # Please change the name of your future generator. 21 # (8, 12, 12, 16, ’aaaaaa’, ’baabaa’, 20.6)

(11)

1 #---my_1_gen.py---2

3 def my_1_gen(*args, gen_exp, gen_exp_cond):

4 for i in args:

5 if not isinstance(i, tuple) and not isinstance(i, str)

6 and not isinstance(i, int)

7 and not isinstance(i, float):

8 return "my_1_gen: One or all received args have ’ \

9 ’type different from string, integer, ’ \

10 ’float and tuple."

11 gen_exp += " "

(12)

13 def iter_gen(args):

14 iter_exp = ""

15 for i in range(len(args)):

16 iter_exp += "for x" + str(i) + " in " \

17 + str(args[i]) + " "

18 return iter_exp

19

20 g_exp = "tuple(" + gen_exp + iter_gen(args) \

21 + gen_exp_cond + ")"

22

(13)
(14)

Неоднорiдна генерацiя програмних кодiв

– це

динамiчне продукування програмами частин програмного

коду iнших програм з використанням рiзних мов.

Триповi приклади:

Генерацiя програмних конструкцiй на певних мовах

програмування з використанням рiзних мов.

Генерацiя програмних кодiв web-додаткiв.

Генерацiя HTML-файлiв, CSS-файлiв, XSD-файлiв,

XML-файлiв, тощо.

(15)

1 #---Wallets.py---2

3 class Wallet:

4 def __init__(self, usd=float(), eur=float(), uah=float()):

5 if isinstance(usd, float):

6 self.usd = usd

7 elif isinstance(usd, int):

8 self.usd = float(usd)

9 if isinstance(eur, float):

10 self.eur = eur

11 elif isinstance(eur, int):

12 self.eur = float(eur)

13 if isinstance(uah, float):

14 self.uah = uah

15 elif isinstance(uah, int):

(16)

17 class PersonalWallet(Wallet):

18 def __init__(self, usd=float(), eur=float(), uah=float(),

19 name=’Name’, surname=’Surname’):

20 Wallet.__init__(self, usd, eur, uah)

21 if isinstance(name, str): 22 self.owner_name = name 23 if isinstance(surname, str): 24 self.owner_surname = surname 25 26 class PremiumPersonalWallet(PersonalWallet):

27 def __init__(self, usd=float(), eur=float(), uah=float(),

28 PersonalWallet.__init__(self, usd + 100, eur + 100,

(17)

1 #---convert_to_html.py---2

3 import os

4 from Wallets import *

5 6 def convert_to_html(target_object): 7 if not os.path.exists(’target_object_html_view’): 8 os.makedirs(’target_object_html_view’) 9 try: 10 path = r’./target_object_html_view/’ + \ 11 target_object.__class__.__name__ + \ 12 ’_target_object_’ + \ 13 str(target_object.__hash__()) + ’.html’ 14 file = open(path, ’x’) 15 file.write(’<style>\n’) 16 file.write(’.my_table{\n’)

(18)

18 file.write(’}\n’)

19 file.write(’\n’)

20 file.write(’.my_table_cell, .my_table_cell_centered {\n’)

21 file.write(’ border: 1px solid black;\n’)

22 file.write(’ border-collapse: collapse;\n’)

23 file.write(’ padding: 5px 5px 5px 5px;\n’)

24 file.write(’}\n’)

25 file.write(’.my_table_cell_centered{\n’)

26 file.write(’ text-align: center;\n’)

27 file.write(’}\n’)

28 file.write(’</style>\n’)

29 file.write(’<h1>’ + target_object.__class__.__name__ +

30 ’_target_object_’ +

31 str(target_object.__hash__()) + ’</h1>\n’)

32 file.write(’<table border="1" class="my_table">\n’)

(19)

34 file.write(’ <td class="my_table_cell"> \ 35 <strong>Attribute name</strong></td>\n’) 36 file.write(’ <td class="my_table_cell"> \ 37 <strong>Attribute value</strong></td>\n’) 38 file.write(’ <td class="my_table_cell"> \ 39 <strong>Attribute type</strong></td>\n’) 40 file.write(’ </tr>\n’)

41 for attribute in target_object.__dict__:

42 file.write(’ <tr>\n’) 43 file.write(’ <td class="my_table_cell">’ + 44 attribute + ’</td>\n’) 45 file.write(’ <td class="my_table_cell_centered">’ + 46 str(target_object.__dict__[attribute]) + 47 ’</td>\n’) 48 file.write(’ <td class="my_table_cell_centered">’ + 49 str(target_object.__dict__[attribute]. 50 __class__.__name__) + ’</td>\n’)

(20)

51 file.write(’ </tr>\n’)

52 target_object_class = target_object.__class__.__name__

53 for i in eval(target_object_class + ’.__dict__’):

54 if i[0] != ’_’ and i[1] != ’_’:

55 file.write(’ <tr>\n’) 56 file.write(’ <td class="my_table_cell">’ + 57 str(target_object_class + ’_’ + i) + 58 ’</td>\n’) 59 file.write(’ <td class="my_table_cell_centered"> \ 60 </td>\n’) 61 file.write(’ <td class="my_table_cell_centered">’ 62 + str(eval(target_object_class + ’.’ + 63 i + ’.__class__.__name__’)) + 64 ’</td>\n’) 65 file.write(’ </tr>\n’) 66 file.write(’</table>\n’) 67 file.close()

(21)

68 except FileExistsError:

69 print(’HTML view for this target_object has already \

70 been created.’)

1

#---main.py---2 from convert_to_html import convert_to_html

3 from Wallets import PersonalWallet

4 from Wallets import PremiumPersonalWallet

5

6 pw = PersonalWallet(usd=23.5, eur=56.26, uah=234,

7 name=’John’, surname=’Smith’)

8 convert_to_html(pw)

9

10 ppw = PremiumPersonalWallet(usd=23.5, eur=56.26, uah=234,

11 name=’Sarah’, surname=’Carter’)

(22)

1 #---PersonalWallet_target_object_-9223363293119356728.html 2 3 <style> 4 .my_table{ 5 border-collapse: collapse; 6 } 7 8 .my_table_cell, .my_table_cell_centered {

9 border: 1px solid black;

10 border-collapse: collapse; 11 padding: 5px 5px 5px 5px; 12 } 13 .my_table_cell_centered{ 14 text-align: center; 15 } 16 </style>

(23)

17 <h1>PersonalWallet_target_object_-9223363293119356728</h1>

18 <table border="1" class="my_table">

19 <tr> 20 <td class="my_table_cell"> 21 <strong>Attribute name</strong> 22 </td> 23 <td class="my_table_cell"> 24 <strong>Attribute value</strong> 25 </td> 26 <td class="my_table_cell"> 27 <strong>Attribute type</strong> 28 </td> 29 </tr> 30 <tr> 31 <td class="my_table_cell">owner_name</td> 32 <td class="my_table_cell_centered">John</td>

(24)

33 <td class="my_table_cell_centered">str</td> 34 </tr> 35 <tr> 36 <td class="my_table_cell">eur</td> 37 <td class="my_table_cell_centered">56.26</td> 38 <td class="my_table_cell_centered">float</td> 39 </tr> 40 <tr> 41 <td class="my_table_cell">owner_surname</td> 42 <td class="my_table_cell_centered">Smith</td> 43 <td class="my_table_cell_centered">str</td> 44 </tr> 45 <tr> 46 <td class="my_table_cell">usd</td> 47 <td class="my_table_cell_centered">23.5</td> 48 <td class="my_table_cell_centered">float</td> 49 </tr>

(25)

50 <tr> 51 <td class="my_table_cell">uah</td> 52 <td class="my_table_cell_centered">234.0</td> 53 <td class="my_table_cell_centered">float</td> 54 </tr> 55 </table> 1 #---PremiumPersonalWallet_target_object_8743735419112.html 2 3 <style> 4 .my_table{ 5 border-collapse: collapse; 6 } 7 8 .my_table_cell, .my_table_cell_centered {

(26)

10 border-collapse: collapse; 11 padding: 5px 5px 5px 5px; 12 } 13 .my_table_cell_centered{ 14 text-align: center; 15 } 16 </style> 17 <h1>PremiumPersonalWallet_target_object_8743735419112</h1>

18 <table border="1" class="my_table">

19 <tr> 20 <td class="my_table_cell"> 21 <strong>Attribute name</strong> 22 </td> 23 <td class="my_table_cell"> 24 <strong>Attribute value</strong> 25 </td>

(27)

26 <td class="my_table_cell"> 27 <strong>Attribute type</strong> 28 </td> 29 </tr> 30 <tr> 31 <td class="my_table_cell">owner_name</td> 32 <td class="my_table_cell_centered">Sarah</td> 33 <td class="my_table_cell_centered">str</td> 34 </tr> 35 <tr> 36 <td class="my_table_cell">eur</td> 37 <td class="my_table_cell_centered">156.26</td> 38 <td class="my_table_cell_centered">float</td> 39 </tr> 40 <tr> 41 <td class="my_table_cell">owner_surname</td>

(28)

42 <td class="my_table_cell_centered">Carter</td> 43 <td class="my_table_cell_centered">str</td> 44 </tr> 45 <tr> 46 <td class="my_table_cell">usd</td> 47 <td class="my_table_cell_centered">123.5</td> 48 <td class="my_table_cell_centered">float</td> 49 </tr> 50 <tr> 51 <td class="my_table_cell">uah</td> 52 <td class="my_table_cell_centered">1234.0</td> 53 <td class="my_table_cell_centered">float</td> 54 </tr> 55 </table>

(29)

Attribute name Attribute value Attribute type owner_name John str owner_surname Smith str usd 23.5 float eur 56.26 float uah 234.0 float PremiumPersonalWallet_target_object_8743735419112

Attribute name Attribute value Attribute type

owner_name Sarah str

owner_surname Carter str

eur 156.26 float

usd 123.5 float

References

Related documents

Наве- демо приклади ІКТ, які є ефективними для роз- витку навичок письма англійською мовою в про- цесі дистанційного та змішаного навчання: засоби

 технології проектування Web-сторінок з використанням таблиць стилів і мови програмування PHP;  технології обробки даних на сервері з використанням мови РНР;

Збільшення вмісту хрому в композиції Сu-Cr створює більш сприятливий (порівняно з Nb) вплив на ерозійну стійкість контактів, у зв’язку з меншою різницею

Якісні критерії оцінювання Необхідний обсяг знань для одержання позитивної оцінки: – знати базові принципи розроблення програмних продуктів

Для визначення діаграми голкової нитки, яка подається в зону шиття, необхідно знайти аналітичні співвідношення залежності руху вічка ниткопритягувача від

З використанням критеріїв Фішера та Стьюде- нта до отриманих експериментально та з використанням моделі WFDS значень швидкості поширення

Вперше встановлено, що високожирові раціони з високим вмістом пальмітинової кислоти (пальмова олія і вершкове масло) в експериментальних моделях з використанням

Оглушення з використанням двоокису вуглецю та інертних газів Негайне або поступове оглушення притомних тварин із використанням суміші газу, що складається