Python’da Modüller Python tanımlarını ve ifadelerini içeren dosyalardır. Fonksiyonlar ise bir mantık üzere çalışan kod parçalarıdır.
>>> pow(2,3) # 8
Python’da hangi fonksiyonlar bulunur?
Python’daki yerleşik fonksiyonları listelemek için dir()
komutunu kullanabiliriz. Eğer dir() argüman olmadan çağrılırsa geçerli scopedaki isimleri döndürür. Aksi takdirde, verilen nesnenin niteliklerini (attributes) ve ondan erişilebilen nitelikleri içeren alfabetik bir liste döndürür.
>>> dir(__builtins__)
[
'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BufferError',
'BytesWarning',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'NameError',
'None',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'ReferenceError',
'RuntimeError',
'RuntimeWarning',
'StandardError',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
'__debug__',
'__doc__',
'__import__',
'__name__',
'__package__',
'abs',
'all',
'any',
'apply',
'basestring',
'bin',
'bool',
'buffer',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'cmp',
'coerce',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'divmod',
'enumerate',
'eval',
'execfile',
'exit',
'file',
'filter',
'float',
'format',
'frozenset',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'intern',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'long',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'quit',
'range',
'raw_input',
'reduce',
'reload',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'unichr',
'unicode',
'vars',
'xrange',
'zip'
]
Herhangi bir fonksiyonun işlevselliğini öğrenmek için yerleşik help
komutunu kullanabiliriz;
>>> help(max)
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
Yerleşik modüller ekstra fonksiyonlar da içerir. Örneğin bir sayının karekökünü elde etmek için math
modülünü eklememiz gerekir .
>>> import math
>>> math.sqrt(16) # 4.0
Bir modüldeki tüm fonksiyonları öğrenmek için fonksiyon listesini bir değişkene atayabilir ve ardından değişkeni yazdırabiliriz.
>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh',
'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign',
'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1',
'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt',
'tan', 'tanh', 'trunc']
__doc__
fonksiyonlara dokümantasyon sağlamak için faydalı bir komut;
>>> math.__doc__
'This module is always available. It provides access to the\nmathematical
functions defined by the C standard.'
Fonksiyonlara ek olarak modüller için de dokümantasyon sağlanabilir. Şöyle adlandırılmış bir dosyanız varsa helloWorld.py
:
"""Modül dokumantasyonu - docstring."""
def sayHello ():
"""Fonksiyon docstring."""
return 'Merhaba Dünya'
Dokümantasyona şu şekilde erişebilirsiniz:
>>> import helloWorld >>> helloWorld.__doc__ 'Modül dokumantasyonu - docstring.' >>> helloWorld.sayHello.__doc__ 'Fonksiyon docstring.'
- Herhangi bir kullanıcı tanımlı tür için, o türün nitelikleri, sınıfının nitelikleri ve yinelemeli olarak temel sınıflarının nitelikleri
dir()
kullanılarak alınabilir.
>>> class MyClassObject(nesne): ... pass ... >>> dir(MyClassObject) [ '__class__' , '__delattr__' , ' __dict__ ' , '__doc__' , '__format__' , '__getattribute__' , '__hash__ ' , ' __init__ ' , ' __module__ ' , ' __new__ ' , ' __reduce__ ' , ' __reduce_ex__ ' , ' __repr__ ' , ' __setattr__ ', '__sizeof__' , '__str__', '__subclasshook__' , '__weakref__' ]
Herhangi bir veri türü yerleşik str
fonksiyonu kullanılarak stringe dönüştürülebilir. Bu fonksiyon bir veri türü print
e argüman olarak aktarıldığında varsayılan olarak çağrılır.
>>> str(123) # "123"
- 1. Python’a Giriş
- 1.1. Değişkenler oluşturma ve değer atama
- 1.2. Girintiler (indentation)
- 1.3. Veri tipleri
- 1.4. Koleksiyon Türleri
- 1.5. Kullanıcı Girdisi
- 1.6. Dahili Modüller ve Fonksiyonlar (Bu yazı)
- 1.7. Python’da Modül Nasıl Oluşturulur
- 1.8. String Fonksiyonları – str ve repr
- 1.9. Pip kullanarak harici modüllerin kurulması
- 1.10. Help – Python’da Yardım Aracı