πŸ“œ ⬆️ ⬇️

If you decide to switch from PHP to Python, then what should you prepare for?

Have you ever thought that once you were too quickly involved in PHP web programming? And now many years have passed, you have a good experience, and you do not think about any other ways to "do" the web, except in PHP. Maybe you have doubts about the correctness of the choice, but it is not clear how to find a way to quickly check it. And I want examples, I want to know how to change specific aspects of the activity.

Today I will try to answer the question: β€œWhat if instead of writing PHP in Python?” .

I myself have been asking this question for a long time. I have been writing PHP for 11 years and even am a certified specialist. I learned to β€œcook” him so that he worked exactly as I needed. And when I once again read the translation of an article about how everything in PHP is bad in HabrΓ©, I was just perplexed. However, turned up the case to transfer to Ruby, and then to Python. At the last, I stopped, and now I will try to tell you PHP-Schnick how we Pythonists live.
')



Article format


The best way to learn a new language is a comparison with a regularly used one, if a new language is not fundamentally different from the current one. A good attempt was made on the Ruby site , but unfortunately there are few examples.

I should also note that I will not compare all aspects of the activity, but only those that will be evident in the first weeks of work with a new language.

Console preparation


I tried to make this article interactive. Therefore, when reading, I strongly recommend typing examples from it in consoles. You will need a PHP console, and better psysh right away :

php -a

Python. bpython ipython, , . :

python

:
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")    #   

~/.pyrc :
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

~/.bashrc :

export PYTHONSTARTUP="${HOME}/.pyrc"
export PYTHONIOENCODING="UTF-8"

, , :
source ~/.bashrc








: , . , :

foreach($a as $value) {
    $formatted = $value.'%';
    echo $formatted;
}
:
for value in a:
    formatted = value + '%'
    print(formatted)


, ! . , , . - , , . . Style Guide, -.

. . 99% IDE , . . 2 , - .


β€” . :

print '0.60' * 5;

print '5' == 5;

$a = array('5'=>true);
print $a[5];

$value = 75;
print $value.'%';

$a='0';
if($a) print 'non zero length';  //       

.

, , , PHP 7. , .

:

>>> print "25" + 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

...
, .

, . , PHP, , 1-2 , .

. , int , None , . . , , , , .

try:
    custom_price = int(request.GET.get('custom_price', 0))
except ValueError:
    custom_price = 0

, , , . - , , . , , . , , . , - , .

, , : str, int, bool, long. .



:

$tak = '';
echo "   $tak  {$tak}.";
echo " ".$tak.".";
echo sprintf("   %s  %1$'.9s.", $tak);

:

etot = ''
var = ''
print(' %s ' % etot)
print(etot + '    ,   ')
print('  %s %s' % (etot, var))
print('  %(etot)s %(var)s' % {'etot': etot, 'var': var})  #    
print('  {} {}'.format(etot, var))
print('  {1} {0}'.format(var, etot))
print('  {etot} {var}'.format(var=var, etot=etot))
print(f'  {etot} {var}')  #   Python 3.6

.


, Python PHP, β€” . :

strpos($a, 'tr');
trim($a);
vs
a.index('tr')
a.strip()

- ?

substr($a, strpos($a, 'name: '));
vs
a[a.index('name: '):]



. Python 2 ( Python 3 β€” ). u , . ( ) Python .

>>> len(' ')
19
>>> len(u' ')
10

PHP 6, .
PHP, , MBString function overloading , , . , .

«»

:
$a = 'Hello.\n';
$a[strlen($a)-1] != "\n"; 

- Python. r, PHP.
a = r'Hello.\n' 
a[-1] != '\n'



. PHP :

var_dump([0=>1, 'key'=>'value']); 

array , PHP array ( ), ( , ). PHP , SPLFixedArray. , , .

Python 3-4 :


PHP β€” , . Python , Computer Science , , . Β« , , Β», β€” . , :



β€” . .

PHP require_once , PHP- . CMS , , , spl_autoload_register .

β€” . , . ( 80 ). :

, tools/logic.py
def is_prime(number):
    max_number = int(sqrt(number))

    for multiplier in range(2, max_number + 1):
        if multiplier > max_number:
            break
        if number % multiplier == 0:
            return False

    return True

main.py. , .
from tools.logic import is_prime

print(is_prime(79))

. : . PHP mysqli_*, pdo_*, memcached_*, , . ?


, , -, , -, , .

? . , , . , . , IDE, , . : , Java C# , .

*args, **kwargs

:

function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.";
}
vs
def makeyogurt(flavour, ftype="acidophilus"):
    return "Making a bowl of %s %s." % (ftype, flavour, )

. : , . PHP, 5.6, :

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
//  
echo add(...[1, 2, 3, 4]);

Python :

def acc(*args, **kwargs):
    total = 0
    for n in args:
        total += n
    return total

print(acc(1, 2, 3, 4))
#  
print(acc(*[1, 2, 3, 4]))

*args β€” list , **kwargs β€” dict .


:

class BaseClass:
    def __init__(self):
        print("In BaseClass constructor")

class SubClass(BaseClass):
    def __init__(self, value):
        super(SubClass, self).__init__()
# ,  Python 3.6:        super().__init__()
        self.value = value

    def __getattr__(self, name):
        print("Cannot found: %s" % name)

c = SubClass(7)
print(c.value)

PHP :


:



, , . , . , - . . , , , :


, , Β« β€” , , β€” Β». , . , , :



PHP , . Python 2 Python 3. , . , Python 3 : , . Β« Β», , Python 2.
Python 2 2019 .


, , , .


?


Python

  , - .



!

: (: dginz, defuz, dsx, Stepanow, Studebecker, svartalf).
: (: yktoo). .
2018: Python 2 3.
2019: Python 3.8 .

Source: https://habr.com/ru/post/221035/


All Articles