🍎Sınıflar ve Miras Alma
Python ile class, interface, meta class, property, static ve class metotları, override vs gibi yapılar
🏰 Class
Nesneye yönelik programlama (OOP) temelini oluşturur
Veri ve metotları gruplandırmamızı ve verimli kodlamamızı sağlar
class Foo(object):
# you couldn't use self. or cls. out here, they wouldn't mean anything
# this is a class attribute
thing = 'athing'
def __init__(self, bar):
# I want other methods called on this instance of Foo
# to have access to bar, so I create an attribute of self
# pointing to it
self.bar = bar
@staticmethod
def default_foo():
# static methods are often used as alternate constructors,
# since they don't need access to any part of the class
# if the method doesn't have anything at all to do with the class
# just use a module level function
return Foo('baz')
@classmethod
def two_things(cls):
# can access class attributes, like thing
# but not instance attribut
🍎 Class Anahtar Kelimeleri
Tip işlemleri yapmak için
print(dir(<tip>))
yazıp çıkan metotlardan kullanacaklarımızı tanımlamamız gerekirÖrn:
int
işlemlerini yapmak içinprint(dir(int))
__add__
,__sub__
...
Çoklu işlemler için
if isinstance(number, int):
yapısı kullanılır
self
Diğer dillerdeki this
anlamına gelir
__init__
Constructor fonksiyonudur
__repr__
Ekrana ne yazılacağı (print
)
__str__
str()
içerisine alındığında yapılacaklar
__rmul__
Ters *
işlemi
__contains__
Dahiliye işlemi
def function(param):
Fonksiyon tanımlama
del p1.age
, del p1
Obje ya da class silme
🤹 Equal Metotu
isinstance
metodu ile aynı sınıftan olup olmadığı kontrol edilirvars(self)
kodu ile sınıfın sahip olduğu tüm değişkenlerdict
olarak alınırdict
verisikey
value
çiftlerine dönüştürülerek otomatik kontrole hazırlanırgetattr
metodu ile verilenkey
ile değişken temsil edilir vevalue
değerine eşitliği kontrol edilirHer koşulun sağlanması durumunda
True
aksi haldeFalse
döndürülür
def __eq__(self, o: object) -> bool:
if isinstance(o,Account):
for key, value in vars(self).items():
if not getattr(o, key) == value:
return False
return True
return False
💎 Properties
class Window(object):
@property
def always_on_top(self):
script = self._render_template('window/win_is_always_on_top.ahk')
resp = self.engine.run_script(script)
return bool(ast.literal_eval(resp))
@always_on_top.setter
def always_on_top(self, value):
if value in ('on', 'On', True, 1):
self.win_set('AlwaysOnTop', 'On')
elif value in ('off', 'Off', False, 0):
self.win_set('AlwaysOnTop', 'Off')
elif value in ('toggle', 'Toggle', -1):
self.win_set('AlwaysOnTop', 'Toggle')
else:
raise ValueError(
f'"{value}" not a valid option')
window = Window()
window.always_on_top = "on"
print(window.always_on_top) # "on"
❔ Class Metotları
🔳 Class metotları sadece class objesine erişir
👮♂️ Obje özelliklerine erişemez (
self
ile erişilir)⚡ Class objesi de kullanılmayacaksa Static metotları tercih ediniz
class Window(object):
@classmethod
def from_mouse_position(cls, engine: ScriptEngine, **kwargs):
script = engine.render_template('window/from_mouse.ahk')
ahk_id = engine.run_script(script)
return cls(engine=engine, ahk_id=ahk_id, **kwargs)
Window.from_mouse_position(...)
⚡ Static Metotlar
📢 Static metotlarda
self
veyacls
parametresi olmaz🕊️ Class içeriklerinden bağımsızdır
class Laptop:
@staticmethod
def details():
print('Hello! I am a laptop.')
laptop1 = Laptop()
laptop1.details()
🍏 Inheritance (Miras)
Miras işlemlerinde object
yerine miras alınacak class adı yazılır.
Üst sınıfın metotlarını ve değişkenlerini barındırır (yani özelliklerine sahip)
Karmaşık programlama mimarilerinde oldukça faydalıdır, düzenli olmayı sağlar
class Rectangle(object):
def __init__(self, height, length):
self.height = height
self.length = length
def area(self): # Alan
return self.height * self.length
def perimeter(self): # Çevre
return 2 * (self.height + self.length)
class Square(Rectangle):
def __init__(self, length):
super(Square, self).__init__(length, length)
s = Square(5)
s.area(), s.perimeter() # (25, 20)
type(s) == Square # False
type(s) == Rectangle # True
isinstance(s, Rectangle) # True
class InputData:
def read(self):
raise NotImplementedError
class PathInputData(InputData):
def __init__(self, path):
super().__init__()
self.path = path
# read tanımlanmazsa hata verir
def read(self):
with open(self.path) as f:
return f.read()
# Miras kontrolü
class BaseClass: pass
class SubClass(BaseClass): pass
issubclass(SubClass, BaseClass)
True
issubclass(SubClass, object)
True
issubclass(BaseClass, SubClass)
False
🍍 Meta Class
class DirectiveMeta(type):
"""
Overrides __str__ so directives with no arguments can be used without instantiation
Overrides __hash__ to make objects 'unique' based upon a hash of the str representation
"""
def __str__(cls):
return f"#{cls.__name__}"
def __hash__(self):
return hash(str(self))
def __eq__(cls, other):
return str(cls) == other
class Directive(SimpleNamespace, metaclass=DirectiveMeta):
"""
Simple directive class
They are designed to be hashable and comparable with string equivalent of AHK directive.
Directives that don't require arguments do not need to be instantiated.
"""
def __init__(self, **kwargs):
super().__init__(name=self.name, **kwargs)
self._kwargs = kwargs
@property
def name(self):
return self.__class__.__name__
def __str__(self):
if self._kwargs:
arguments = ' '.join(str(value) for key, value in self._kwargs.items())
else:
arguments = ''
return f"#{self.name} {arguments}".rstrip()
def __eq__(self, other):
return str(self) == other
def __hash__(self):
return hash(str(self))
⭐ Class Örnekleri
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # John
print(p1.age) # 36
💎 Enumeration
Resmi dokümantasyon için buraya bakabilirsin.
Sıralı ve sabit veriler oluşturmak için kullanılır
from enum import Enum
ile projeye dahil edilirEnumlarda değer eşitliği için
<enum>.value == <value>
kullanınEnumları değerler ile oluşturmak için
<Enum>(<value>)
yapısını kullanınEnum ile enum oluşturabilirsiniz
<Enum>(<enum>)
Değişkenin enum veya değer tuttuğundan emin olmadığınız durumlarda üstteki yapıyı kullanın
from enum import Enum
from typing import Union # Tip belirtme amaçlı eklenmiştir
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# Temel erişimler
Color # <enum 'Color'>
Color.RED.value # 1
Color.RED.name # RED
type(Color.RED) # <enum 'Color'>
Color(1) # <Color.RED: 1>
Color(Color.BLUE) # <Color.BLUE: 3>
# Enum tanımlama
color_var: Union[str, Color] # str veya Color tipinde bir obje
color: Color = Color(color_var) # Enum ile enum objesi oluşturabilirz
color: Color = Color.RED # Direkt olarak enum atama
# Enum değerlerine erişme
color = Color.RED
color.value == 1 # True
color == 1 # False
color.name == "RED" # True
color == "RED" # False
isinstance(Color.GREEN, Color) # True
🔶 Multi Value Enum
Birden fazla değere sahip enum sınıfı tanımlamaya olanak sağlar
pip install aenum
ile gerekli paket yüklenmelidir
from aenum import MultiValueEnum
class DType(MultiValueEnum):
float32 = "f", 8
double64 = "d", 9
>>> DType("f")
<DType.float32: 'f'>
>>> DType(9)
<DType.double64: 'd'>
Last updated
Was this helpful?