TelenkovDmitry před 5 měsíci
rodič
revize
a8a8152481

+ 22 - 0
courses/python_oop/meta/metaclass_1.py

@@ -0,0 +1,22 @@
+'''
+Аргумент metaclass указывает на то, какой класс учавствует при создании класса.
+'''
+
+
+class Person(object, metaclass=type):
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+
+    def greeting(self):
+        return f'Hi, I am {self.name}. I am {self.age} yers old.'
+    
+
+class Student(Person, metaclass=type):
+    def __init__(self, name, age, major):
+        super().__init__(name, age)
+        self.major = major
+
+
+
+        

+ 36 - 0
courses/python_oop/meta/metaclass_2.py

@@ -0,0 +1,36 @@
+
+class CustomType(type):
+    def __new__(cls, name, bases, class_dict):
+        print('Запуск создания нового типа данных!')
+        # делегируем создание объекта через super 
+        # в данном случае родитель - это класс type
+        cls_obj = super().__new__(cls, name, bases, class_dict)
+        cls_obj.say_hello = lambda self: f'Hello, my name is {self.name}'
+        return cls_obj
+    
+class Person(metaclass=CustomType):
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+
+    def greeting(self):
+        return f'Hi, I am {self.name}. I am {self.age} years old.'
+    
+
+def test_1():
+    print(Person)
+    print('Type of Person is', type(Person))
+    print('Person is isinstance of CustomType', isinstance(Person, CustomType))
+    print('Person is isinstance of type', isinstance(Person, type))
+
+    p = Person('Ivan', 25)
+    print(p.greeting())
+    print(p.say_hello())
+
+
+def main():
+    test_1()
+
+
+if __name__ == '__main__':
+    main()

+ 64 - 0
courses/python_oop/meta/metaclass_3.py

@@ -0,0 +1,64 @@
+'''Параметры метакласса'''
+
+'''Шаблон для создания метакласса'''
+class NewMetaclass(type):
+    def __new__(mcls, name, bases, cls_dict):
+        return super().__new__(mcls, name, bases, cls_dict)
+    
+class MyClass(metaclass=NewMetaclass):
+    pass
+
+
+'''Дополнительные аргументы'''
+class Metaclass(type):
+    def __new__(cls, name, bases, cls_dict, arg1, arg2, arg3=None):
+        print('Запуск создания нового типа данных', arg1, arg2, arg3)        
+        return super().__new__(cls, name, bases, cls_dict)
+    
+class MyClass1(metaclass=Metaclass, arg1=10, arg2=20, arg3=30):
+    pass
+
+class MyClass2(metaclass=Metaclass, arg1=10, arg2=5):
+    pass
+
+
+'''Передача коллекции атрибутов'''
+class AutoClassAttrib(type):
+    def __new__(cls, name, bases, cls_dict, extra_attrs=None):
+        new_cls = super().__new__(cls, name, bases, cls_dict)
+        if extra_attrs:
+            print('Creating class with some extra attributes: ', extra_attrs)
+            for attr_name, attr_value in extra_attrs:
+                setattr(new_cls, attr_name, attr_value)
+        return new_cls
+    
+class Account(metaclass=AutoClassAttrib,
+              extra_attrs=[
+                  ('account_type', 'debit'),
+                  ('city', 'Paris'),
+                  ('overdraft', 1000)]
+            ):
+    pass
+
+
+def test_1():
+    print(Account.__dict__)
+    print('-' * 15)
+
+    class Person(object, metaclass=AutoClassAttrib,
+                 extra_attrs=[
+                     ('country', 'Tailand'),
+                     ('citizen', True)
+                 ]):
+        def __init__(self, name, age):
+            self.name = name
+            self.age = age
+
+    print(Person.__dict__)
+
+def main():
+    test_1()
+
+
+if __name__ == '__main__':
+    main()

+ 0 - 22
courses/python_oop/meta/type.py

@@ -1,22 +0,0 @@
-'''
-Любой класс относится к типу данных type и является его экземпляром.
-'''
-class Person:
-    def __init__(self, name, age):
-        self.name = name
-        self.age = age
-
-    def greeting(self):
-        return f'Hi, I am {self.name}. I am {self.age} years old'
-
-def test_1():
-    print(isinstance(Person, type))
-    print(type(Person))
-
-
-def main():
-    test_1()
-
-if __name__ == '__main__':
-    main()
-

+ 48 - 0
courses/python_oop/meta/type_1.py

@@ -0,0 +1,48 @@
+'''
+Любой класс относится к типу данных type и является его экземпляром.
+'''
+class Person:
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+
+    def greeting(self):
+        return f'Hi, I am {self.name}. I am {self.age} years old'
+
+def test_1():
+    print(isinstance(Person, type))
+    print(type(Person))
+
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+class_body = """
+def __init__(self, name, age):
+    self.name = name
+    self.age = age
+
+def greeting(self):
+    return f'Hi, I am {self.name}. I am {self.age} years old.'
+"""
+
+def test_2():
+    class_namespace = {}
+
+    exec(class_body, globals(), class_namespace)
+
+    class_name = 'NewPerson'
+    class_bases = tuple()
+    NewPerson = type(class_name, class_bases, class_namespace)
+
+    print(NewPerson)
+    print(type(NewPerson))
+    print(NewPerson.__dict__)
+
+
+
+def main():
+    # test_1()
+    test_2()
+
+if __name__ == '__main__':
+    main()
+

+ 46 - 0
courses/python_oop/meta/type_2.py

@@ -0,0 +1,46 @@
+'''
+Класс-насдник от type.
+'''
+
+class CustomType(type):
+    def __new__(cls, name, bases, class_dict):
+        print('Запуск создания нового типа данных')
+        # делегируем создание объекта через super 
+        # в данном случае родитель это класс type
+        cls_obj = super().__new__(cls, name, bases, class_dict)
+        cls_obj.say_hello = lambda self: f"Hello, my name is {self.name}"
+        return cls_obj
+    
+
+class_body = """
+def __init__(self, name, age):
+    self.name = name
+    self.age = age
+
+def greeting(self):
+    return f'Hi, I am {self.name}. I am {self.age} years old.'
+"""
+    
+def test_1():
+    class_namespace = {}
+    exec(class_body, globals(), class_namespace)
+
+    Person = CustomType('Person',(), class_namespace)
+
+    print(Person)
+    print('Type of Person is', type(Person))
+    print('Person is isinstance of CustomType', isinstance(Person, CustomType))
+    print('Person is isinstance of type', isinstance(Person, type))
+    
+    p = Person('Ivan', 25)
+    print(p.greeting())
+    print(p.say_hello())
+
+
+
+def main():
+    test_1()
+
+if __name__ == '__main__':
+    main()
+    

+ 26 - 0
courses/python_oop/meta/type_3.py

@@ -0,0 +1,26 @@
+
+class_body = """
+def __init__(self, name, age):
+    self.name = name
+    self.age = age
+
+def description(self):
+    return f'{self.name} is {self.age} years old'
+
+def speak(self, sound):
+    return f'{self.name} says {sound}'
+"""
+
+class_namespace = {}
+
+exec(class_body, globals(), class_namespace)
+Dog = type('Dog', (), class_namespace)
+
+curt = Dog("Curt", 4)
+print(curt.name)
+print(curt.age)
+print(curt.description())
+print(curt.speak('Wo'))
+print(curt.speak('Bow'))
+print(isinstance(curt, Dog))
+