🙄Разминка для ума!
Треугольник Серпинского, интересная фигура которую построить достаточно просто.
Алгоритм такой:
1. создаём любые 3 точки на плоскости
2. из этих точек случайно выбираем любую, как начальную
3. случайно выбираем любую точку из этих же трёх точек как цель
4. перемещаемся в сторону цели на половину расстояния
5. повторяем бесконечно с пункта 3
Если сделать достаточно много итераций то вырисовывается интересная фигура. Треугольник, в который вписаны более мелкие треугольники. Это самый настоящий фрактал!
Я собрал пример построения такой фигуры на базе Qt.
🌎 Код можно посмотреть здесь.
С помощью paintEvent я рисую точки по озвученному алгоритму. Каждые 10 секунд либо по клику на виджете строится следующий треугольник.
Особенности примера:
🔸 Атрибут Qt.WA_OpaquePaintEvent позволяет сохранить то, что было нарисовано в прошлой итерации. Таким образом мы видим постепенное наполнение точек а не мелькающую одну точку.
🔸QTimer позволяет создавать отложенные вызовы один раз или с повторением через интервал.
🔸QColor.fromHsv() позволяет создать рандомный но предсказуемый цвет с помощью HSV схемы. Не слишком светлый и не слишком тёмный но всегда с разный. Рандомизации подвергается только смещение по цветовому кругу (Hue), яркость (Value) и насыщенность (Saturation) можно контролировать отдельно в своих пределах или оставить статичными. Обычный рандом цвета по RGB не даёт такой предсказуемый результат.
🔸 Каждый новый цикл с новым треугольником предварительно затемняет предыдущие через этот вызов
painter.fillRect(rec, QColor(0, 0, 0, 100))
То есть полупрозрачный цвет. Таким образом, чем старше треугольник, тем он темней.
Если сделать виджет фулскрин, то у нас получится некий ScreenSaver)))
🔸 Да, я знаю, что рисование в Qt не самый лучший способ сделать этот пример) Скорее всего самый НЕподходящий. Попробуйте сделать тоже самое но другими средствами.
#qt#source#tricks
https://docs.python.org/3/library/functions.html#classmethod
classmethod(function)
Return a class method for function.
A #class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.
It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.
For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
🧠"Zamonaviy dizayn" kursida biznes savodxonligi va tadbirkorlik ko‘nikmalari
🏛 Biznes va tadbirkorlik oliy maktabi hamda Xalqaro inklyuziv hab hamkorligida “Zamonaviy dizayn” kursiga “Biznes savodxonligi” fani qo‘shimcha fakultativ dars sifatida kiritildi.
➕ Dasturda o‘quvchilar nafaqat ijodiy, balki tadbirkorlik va biznes ko‘nikmalarini ham o‘rganadilar. Ular biznes turlari, tashkiliy-huquqiy asoslar, soliq imtiyozlari, xarajatlarni tahlil qilish, tannarxni hisoblash, narxlarni shakllantirish va foydani baholash kabi muhim ko‘nikmalarni egallaydilar. Bu jarayonda Oliy biznes maktab professori D. Rasulova va malakali mutaxassis B. Ishmuxamedov kabi tajribali o‘qituvchilar o‘quvchilarga bilim va tajribalar ulashdilar.
#GSBE#GraduateSchool#Class#Academic#Study
🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube
http://www.wikipython.com/other-concepts/anatomy-of-a-class/
It seems obvious, but note that you must define a class before you use it.
When you create a #class, it establishes its own namespace and all its own local variables (except global definitions) exist only inside that #namespace. They do not interact with other variables of the same name outside it. This leads us to one very important “feature” of classes that you need to know. If you use the same word to designate some specific value both inside and outside the class blueprint, the instance value will take precedence when you try to use that value.
#learn
https://en.wikipedia.org/wiki/Single_responsibility_principle
The #single_responsibility_principle is a computer programming principle that states that every #module or #class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as, "A class should have only one reason to change."
https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
Mixing #static, #class and #abstract methods
When building classes and inheritances, the time will come where you will have to mix all these methods decorators. So here's some tips about it.
Keep in mind that declaring a method as being abstract, doesn't freeze the prototype of that method. That means that it must be implemented, but it can be implemented with any argument list.