Python لغة برمجة ديناميكية وذات أنواع قوية. وهي تعتمد كلا من نمط البطة والتنميط التدريجي، عبر تلميحات الأنواع. تدعم أساليب البرمجة الأمرية والتعريفية (مثل البرمجة الوظيفية) والكائنية التوجّه، لكن داخليًا كل شيء في Python كائن.
يولي Python اهتمامًا كبيرًا بوضوح الكود، ويستخدم (على غرار Haskell) الإزاحة ذات الدلالة للإشارة إلى تعريفات الدوال والطرق والأصناف.
أنشأ Guido van Rossum لغة Python وأُصدرت أول مرة عام 1991. وتدير مؤسسة Python البرمجية موارد تطوير Python وCPython وتوجّهها، وتتلقى مقترحات لتغيير اللغة من أعضاء المجتمع عبر مقترحات تحسين Python أو PEPs.
يمكن العثور على التوثيق الكامل للإصدار الحالي في docs.python.org.
يقدّم هذا المفهوم الأول 4 ميزات رئيسية من ميزات لغة Python:
def والكلمة المفتاحية return)،بشكل عام، يتبع المحتوى والاختبارات وأدوات التحليل في مسار Python اصطلاحات الأسلوب الواردة في PEP 8 وPEP 257 لأسلوب كتابة كود Python، مع اقتراح إضافي (قوي) بعدم استخدام أسماء متغيرات من حرف واحد.
ويوضّح فلسفة Python (PEP 20) وما معنى أن تكون Pythonic؟ مبادئ إضافية.
في مسار Python، تُكتب المتغيرات دائمًا بصيغة snake_case، والثوابت بصيغة SCREAMING_SNAKE_CASE
في Python، لا توجد كلمات مفتاحية تُستخدم عند إنشاء المتغيرات أو الثوابت.
بدلًا من ذلك، يمكن للمبرمجين ربط الأسماء (وتسمى أيضًا المتغيرات) بأي نوع من الكائنات باستخدام عامل الإسناد =: <name> = <value>.
ويمكن إعادة إسناد الاسم (أو إعادة ربطه) بقيم مختلفة (أنواع كائنات مختلفة) طوال فترة وجوده.
على سبيل المثال، يمكن إعادة إسناد my_first_variable مرات كثيرة باستخدام =، ويمكن أن يشير إلى أنواع كائنات مختلفة مع كل إعادة إسناد:
>>> my_first_variable = 1 # my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2 # my_first_variable re-assigned to integer value 2.
>>> print(type(my_first_variable))
<class 'int'>
>>> print(my_first_variable)
2
>>> my_first_variable = "Now, I'm a string." # <--You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>
>>> my_first_variable = 'You can call me "str".' # <--Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".
>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>
>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})
الثوابت أسماء يُقصد بها أن تُسند مرة واحدة فقط في البرنامج.
ويُستحسن تعريفها على مستوى الوحدة (الملف)، وعادة ما تكون مرئية لجميع الدوال والأصناف في البرنامج.
واستخدام SCREAMING_SNAKE_CASE إشارة إلى أنه لا ينبغي إعادة إسناد الاسم أو تغيير قيمته.
# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16
# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"
في Python، تُغلَّف وحدات الوظائف في الدوال، وهي نفسها كائنات (إنها سلاحف إلى القاع).
يمكن تنفيذ الدوال بمفردها، أو تمريرها كوسائط إلى دوال أخرى، أو تضمينها داخل دوال، أو ربطها بصنف. وعندما تُربط الدوال باسم صنف تُسمى طرقًا. ويمكن تجميع الدوال والأصناف المرتبطة (مع طرقها) في الملف نفسه أو الوحدة نفسها، واستيرادها جزئيًا أو كليًا للاستخدام في برامج أخرى.
تبدأ الكلمة المفتاحية def تعريف دالة.
ويمكن أن تحتوي كل دالة على صفر أو أكثر من المعاملات الشكلية داخل الأقواس الهلالية ()، يتبعها نقطتان :.
وتبدأ عبارات جسم الدالة في السطر التالي لـ def ويجب أن تكون مُزاحة في كتلة:
# The body of a function is indented by 2 spaces & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
total = number_one + number_two
print(total)
>>> add_two_numbers(3, 4)
7
# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
... result = number_one + number_two + number_three # This was indented by 4 spaces.
... print(result) # <--This was only indented by 3 spaces.
...
...
File "<stdin>", line 3
print(result)
^
IndentationError: unindent does not match any outer indentation level
تُرجع الدوال قيمة أو كائنًا بشكل صريح عبر الكلمة المفتاحية return:
# Function definition on first line, explicit return used on final line.
def add_two_numbers(number_one, number_two):
return number_one + number_two
# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7
# Assigning the function call to a variable and printing
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11
الدوال التي لا يتبع فيها return تعبير صريح ستُرجع ضمنًا كائن None.
وسنغطي تفاصيل None في مفهوم لاحق.
ولأغراض هذا التمرين وهذا الشرح، None قيمة مؤقتة تمثل لا شيء، أو القيمة الفارغة null:
# This function will return `None`
def square_a_number(number):
square = number * number
return # <-- note that this return is not followed by an expression
# Calling the function in the Python shell appears
# to not return anything at all.
>>> square_a_number(2)
>>>
# Using print() with the function call shows that
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None
الدوال التي تحذف return ستُرجع أيضًا ضمنًا كائن None.
وهذا يعني أنه إذا لم تستخدم return في دالة، فسيُرجع Python كائن None نيابة عنك.
# This function omits a return keyword altogether
def add_two_numbers(number_one, number_two):
result = number_one + number_two
>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None
# Assigning the function call to a variable and printing
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None
تُستدعى الدوال أو تُشغَّل بكتابة اسمها متبوعًا بـ ().
ويُستخدم الترميز النقطي (.) لاستدعاء الدوال المعرّفة داخل صنف أو وحدة.
>>> def raise_to_power(number, power):
... return number ** power
...
>>> raise_to_power(3,3) # Invoking the function with the arguments 3 and 3.
27
# A mis-match between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'
# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text) # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper() # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'MY SILLY SENTENCE FOR EXAMPLES.'
# Importing the math module
>>> import math
>>> math.pow(2,4) # <--Calling the pow() function from the math module.
16.0
تبدأ التعليقات في Python بعلامة # ليست جزءًا من سلسلة نصية، وتنتهي بنهاية السطر.
وخلافًا لكثير من لغات البرمجة الأخرى، لا يدعم Python علامات التعليق متعددة الأسطر.
ويجب أن يبدأ كل سطر في كتلة التعليق بالمحرف #.
يتجاهل المفسّر التعليقات:
# This is a single line comment.
x = "foo" # This is an in-line comment.
# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.
يمكن أن تكون عبارة جسم الدالة الأولى نصًّا توثيقيًّا اختياريًّا، يلخّص بإيجاز الغرض من الدالة أو الكائن. وتُعلَن النصوص التوثيقية باستخدام ثلاث علامات اقتباس مزدوجة (""") مُزاحة بالمستوى نفسه الذي في كتلة الكود:
# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword Arguments:
real (float): The real part of the number (default 0.0)
imag (float): The imaginary part of the number (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
تقرأ أدوات التوثيق الآلية النصوص التوثيقية، وتُرجَع عند استدعاء السمة الخاصة .__doc__ على اسم الدالة أو الطريقة أو الصنف.
ويُنصح بها للبرامج من أي حجم تحتاج إلى توثيق، واصطلاحاتها موضحة في PEP257.
يمكن أن تعمل النصوص التوثيقية أيضًا كـاختبارات وحدة خفيفة، يمكن لـ PyTest قراءتها وتشغيلها، أو عبر استيراد وحدة doctest.
وسنغطي الاختبار وdoctest في مفهوم لاحق.
# An example on a user-defined function using a Google style docstring.
>>> def raise_to_power(number, power):
"""Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
"""
return number ** power
...
# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
...
# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to 'utf-8'.
errors defaults to 'strict'.