PHPからPythonに切り替えることにした場合、何を準備する必要がありますか?

かつてPHPのWebプログラミングにあまりにも早く関わったと思ったことはありますか? そして、もう何年も経ちました。良い経験があり、PHPを除いて、ウェブを「作る」他の方法を考えていません。 正しい選択について疑問があるかもしれませんが、すぐに確認する方法を見つける方法は明確ではありません。 そして、例を挙げたい、活動の特定の側面がどのように変化するかを知りたい。

今日は、 「PHPの代わりにPythonで書くとしたらどうでしょう?」という質問に答えようとします。

私自身はこの質問を長い間疑問に思っていました。 私は11年間PHPで書いており、認定スペシャリストでもあります。 必要に応じて正確に機能するように、「調理」する方法を学びました。 そして、Habré でPHPのすべてがいかに悪いかについての記事の翻訳をもう一度読んだとき、私は単に当惑しました。 しかし、このケースはRubyに転送され、次にPythonに転送されました。 最後の1つで停止しました。次に、PHP-shnikに、私たちがパイニストのように感じていることを伝えようとします。




記事の形式


新しい言語が現在の言語と根本的に異ならない場合、新しい言語を習得する最良の方法は、定期的に使用される言語と比較することです。 Rubyサイトで良い試みがなされましたが、残念ながらいくつかの例があります。

また、アクティビティのすべての側面を比較するのではなく、新しい言語での作業の最初の数週間で目を引くものだけを比較することに注意する必要があります。

コンソールの準備


この記事をインタラクティブにしようとしました。 したがって、本を読むときは、コンソールからサンプルを募集することを強くお勧めします。 PHPコンソールまたはより良いpsyshがすぐに必要になります。

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]))

*argslist , **kwargsdict .


:

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/J221035/


All Articles