Ben genelde kendi işlerim için kod yazdığımda fonksiyonsuz yada tekrarlanacak işlemlerde basit fonksyonlar yaziyorum.
Nesne tabanlı dışında Pythonda birçok şey biliyorum.
Nasil fonksiyonel yapıları kodu inceler incelemez anlamış olmam için ne tür araştırmalar yapmalıyım.
Geçen bir arkadaş py dosyanı attı. İçinde yüzlerce fonksiyon vardı. Fonksiyonlarda yorum satırları yoktu. Çok birşey anlamadım.
Python Fonksiyonel Yapılarını Nasıl Bir Bakışta Anlarım.
3
●156
- 29-10-2024, 09:24:15Hocam bunun tek cevabı proje geliştirmek.
Yakın zamanda hayatımıza giren yapay zeka yüzünden bir çok yeni yazılımcı arkadaş oradan destek alıyor fakat öğrenmeyi unutuyorlar, önceden 1 satırlık kod için 3 4 saat araştırma yapmamız gerekebiliyordu.
Bu gün ben yapay zekadan yardım aldığımda bana yazdığı çoğu fonksiyona müdahale edemiyorum, bazen çok uzatıyor bazen de alakasız sonuçlarla karşılaşıyorum, önceden araştırma yaparken ingilizce olarak aratır ardından sayfadaki kodları incelerdik, kodlara bakarak yapıyı anlar işe yarayanları deneyerek mevcut koda entegre ederdik.
Size tavsiyem hangi alanda proje geliştiriyorsanız onu Google üzerinde aramanız hatta sonuna "stackoverflow" kelimesi eklemenizi öneririm, örn: "python list add string site:stackoverflow.com" şeklinde, sizin aldığınız hatayı veya yapmak istediğiniz şeyi birileri önceden yapmıştır veya hatayı almıştır, bu gün ki yazılım dediğimiz sistem bir çok yazılımın birleştirilerek kütüphane oluşturulmasından ibaret. - 30-10-2024, 12:33:33Nasilsin hocam.A.AY adlı üyeden alıntı: mesajı görüntüle
Uzun zamandir yazilimla ilgilenmiyorum.
Eger kodlamada cok fazla fonksiyon varsa kesinlikle icinde aciklama olmasi gerekir yoksa isin icinden cikmazsin. Bazen eski yazdigim projelere bakiyorum, not eklemedigim icin ne oldugunu ben bile anlamakta zorluk cekiyorum. Ancak kodu class yapisiyla yazarsdan cok not eklemesende kodu daha rahat algiliyorsun.
Yanlis hatirlamiyorsam pythonda bir class yapisinda kod yazmak var birde Procedural dedigimiz yukardan asaga yazilan kod yapisi var. Icinde cok fazla fonksiyon olan ve Procedural seklinde class yapisiz yazilan bir kodlamada isler bir noktadan sonra raydan cikiyor. Ne nerden geldi nereye gidecek kafa karisikligina sebep oluyor.
Bunu asmanin tek yolu Class yapisi ile kodlamayi yazmak ve birkac modulde
bunu tasarlamak. Boyle olunca kod inanilmaz duzenli ve basit oluyor. Ben o seviyeye gelememistim.
Bak mesela sana bir kahve makinasinin nasil kodlandigini gondereyim. Angela Ju derslerinden birisiydi. Ustteki arkadasa katiliyorum. Kodla ilgilendikce inanilmaz seyler yapiyorsun. Ben zamaninda bir siteden oto uye olup whois keylerini cekmek icin bir bot yapmistim. Birde bu keylerle domain sorgulamasi yapiyordum. Kodu nasil yaptigima ben bile bugun anlam veremiyorum. O kodlari nasil yazdim diye sasiriyorum. Ilgilenmek lazim projeler gerceklestirmek lazim. Ozellikle Class yapisinda yazmak lazim.
Mesela blackjack oyunu yazmisti Angela you. Kart destesindeki tum kartlari bile class yapisinda nesne olarak yazip, tum kodlamada herhangi bir yerde kolayca kullanabilmisti.
Kahve makinasi:
main.py
from coffee_maker import CoffeeMaker from menu import Menu from money_machine import MoneyMachine money_machine = MoneyMachine() coffee_maker = CoffeeMaker() menu = Menu() is_on = True while is_on: options = menu.get_items() choice = input(f"What would you like? ({options}): ") if choice == "off": is_on = False elif choice == "report": coffee_maker.report() money_machine.report() else: drink = menu.find_drink(choice) if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment( drink.cost ): coffee_maker.make_coffee(drink)
menu.py
class MenuItem: """Models each Menu Item.""" def __init__(self, name, water, milk, coffee, cost): self.name = name self.cost = cost self.ingredients = {"water": water, "milk": milk, "coffee": coffee} class Menu: """Models the Menu with drinks.""" def __init__(self): self.menu = [ MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5), MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5), MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3), ] def get_items(self): """Returns all the names of the available menu items""" options = "" for item in self.menu: options += f"{item.name}/" return options def find_drink(self, order_name): """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None""" for item in self.menu: if item.name == order_name: return item print("Sorry that item is not available.")
money_machine.py
class MoneyMachine: CURRENCY = "$" COIN_VALUES = {"quarters": 0.25, "dimes": 0.10, "nickles": 0.05, "pennies": 0.01} def __init__(self): self.profit = 0 self.money_received = 0 def report(self): """Prints the current profit""" print(f"Money: {self.CURRENCY}{self.profit}") def process_coins(self): """Returns the total calculated from coins inserted.""" print("Please insert coins.") for coin in self.COIN_VALUES: self.money_received += ( int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin] ) return self.money_received def make_payment(self, cost): """Returns True when payment is accepted, or False if insufficient.""" self.process_coins() if self.money_received >= cost: change = round(self.money_received - cost, 2) print(f"Here is {self.CURRENCY}{change} in change.") self.profit += cost self.money_received = 0 return True else: print("Sorry that's not enough money. Money refunded.") self.money_received = 0 return False
coffee_maker.py
class CoffeeMaker: """Models the machine that makes the coffee""" def __init__(self): self.resources = { "water": 300, "milk": 200, "coffee": 100, } def report(self): """Prints a report of all resources.""" print(f"Water: {self.resources['water']}ml") print(f"Milk: {self.resources['milk']}ml") print(f"Coffee: {self.resources['coffee']}g") def is_resource_sufficient(self, drink): """Returns True when order can be made, False if ingredients are insufficient.""" can_make = True for item in drink.ingredients: if drink.ingredients[item] > self.resources[item]: print(f"Sorry there is not enough {item}.") can_make = False return can_make def make_coffee(self, order): """Deducts the required ingredients from the resources.""" for item in order.ingredients: self.resources[item] -= order.ingredients[item] print(f"Here is your {order.name} ☕️. Enjoy!")Bakalim bu sene egitimlere geri donecegim.
Python sonra Django - 30-10-2024, 13:49:19Teşekkür ederim değerli bilgiler için.Messi adlı üyeden alıntı: mesajı görüntüle
@Messi; Class sistemi bana karmaşık geliyordu. Kodumu chatgpt verip class a çevir dedim. Kolaymış. Gereksiz gözümde büyütmüşüm.
En kısa zamanda pratik yapıp öğrenicem.
import pandas as pd from datetime import datetime class CSVProcessor: def __init__(self, file_path): # CSV dosyasını yükle self.data = pd.read_csv(file_path) # Her bir sütunu ayrı listelere ayır self.tarih_list = self.data['time'].tolist() self.open_list = self.data['open'].tolist() self.high_list = self.data['high'].tolist() self.low_list = self.data['low'].tolist() self.fiyat_list = self.data['close'].tolist() self.rsi_list = self.data['RSI'].tolist() self.macd_list = self.data['MACD'].tolist() self.histogram_list = self.data['Histogram'].tolist() # Yeni sütun self.k_list = self.data['%K'].tolist() # Stochastic RSI self.dpo_list = self.data['Detrended Price Oscillator'].tolist() # Yeni sütun # Zaman damgasını okunabilir tarih formatına çevir self.tarih_list = [datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') for ts in self.tarih_list] # NaN değerli indeksleri belirle self.nan_index = [j for j, i in enumerate(self.macd_list) if isinstance(i, str) and i.lower() == 'nan'] def process_data(self): # NaN indekslerine göre listeleri düzenle nan_index_boyut = len(self.nan_index) tarih_list1 = self.tarih_list[nan_index_boyut:] fiyat_kapanis1 = self.fiyat_list[nan_index_boyut:] fiyat_acilis1 = self.open_list[nan_index_boyut:] fiyat_en_yuksek1 = self.high_list[nan_index_boyut:] fiyat_en_dusuk1 = self.low_list[nan_index_boyut:] rsi_list1 = self.rsi_list[nan_index_boyut:] macd_list1 = self.macd_list[nan_index_boyut:] histogram_list1 = self.histogram_list[nan_index_boyut:] stokastik_rsi1 = self.k_list[nan_index_boyut:] dpo_list1 = self.dpo_list[nan_index_boyut:] return { "tarih_list1": tarih_list1, "fiyat_kapanis1": fiyat_kapanis1, "fiyat_acilis1": fiyat_acilis1, "fiyat_en_yuksek1": fiyat_en_yuksek1, "fiyat_en_dusuk1": fiyat_en_dusuk1, "rsi_list1": rsi_list1, "macd_list1": macd_list1, "histogram_list1": histogram_list1, "stokastik_rsi1": stokastik_rsi1, "dpo_list1": dpo_list1 }