かつて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
- Python — (. ). Python — , , , , , . : Ruby.
- PHP — . PHP — , , , . , - , PHP . : JavaScript, Lua, Perl.
- .py . <?PHP , .
- , php.ini. , ( PYTHONIOENCODING). , , , , . , , . ( ). php.ini .
- . , , PHP, . .
- $ (, PHP Perl, — ).
- . , , , , . ( Python 3.8 -, . . PEP 572)
- Python .pyc ( Python < 3.3 PYTHONDONTWRITEBYTECODE), - , . , . IDE . PHP APC, .pyc .
- : NULL, TRUE, FALSE — None, True, False .
: , . , :
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);
vsa.index('tr')
a.strip()
- ?
substr($a, strpos($a, 'name: '));
vsa[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 :
- list — .
a = [1, 2, 3] #
a[10] = 11 #
# > IndexError: list assignment index out of range
a.append(11) #
del a[0] #
a.remove(11) #
- dict — . , ( PHP ).
d = {'a': 1, 'b': 2, 'c': 3} #
d[10] = 11 #
d[True] = False # (, , , , )
del d[True] #
- tuple — . . .
t = (True, 'OK', 200, ) #
t[0] = False #
# > TypeError: 'tuple' object does not support item assignment
del t[True] #
# > TypeError: 'tuple' object doesn't support item deletion
t = ([], ) # (, , , , )
t[0].append(1)
# > a == ([1], )
- set — . , .
s = set([1,3,4])
s[0] = False #
# > TypeError: 'set' object does not support indexing
s.add(5) #
s.remove(5) #
#
s | s #
s & s #
s - s #
s ^ s #
PHP — , . Python , Computer Science , , . « , , », — . , :
- -: tuple, set, list dict — , , .
- -: list dict.
- -: , -, , , -, .
- -: dict — OrderedDict.
— . .
PHP
require_once , PHP- . CMS , , ,
spl_autoload_register .
— . , . ( 80 ). :
,
tools/logic.pydef 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.";
}
vsdef 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 :
- self $this . self (, ). , Python (, , ).
- PHP, . __construct — __init__. __get — __getattr__ ..
- new. — , .
- . super , . parent:: PHP — .
:
- .
- public, protected, private. runtime , , - . Reflection. protected — . / _%ClassName%__%varname%, .
- static, . Python . Singleton , . , , .
- . , , ( bool), , , . . , . , .
, , . , . , - . . , , , :
, , « — , , — ». , . , , :
- , , , ( ).
- strlen count — len.
- ..
PHP , . Python 2 Python 3. , . , Python 3 : , . « », , Python 2.
Python 2 2019 .
, , , .
- composer -> pip
- mod_php -> mod_wsgi
- nginx + php-fpm -> nginx + uwsgi + uwsgi_python
- daemon.io -> tornado, twisted
- Zend Framework -> Django
- phalcon -> falcon
?
- , , .
- .
- , .
- ( ).
- , ( , ).
- (- ).
Python
, - .
- 1- : Dive Into Python, 2- 7- . . 10 Project Euler. , . - bash-, ls BusyBox - . , - , , . , , PHP-, .
- 2- : Django . : , , , , , .
- 3- : , , .
!
: (:
dginz,
defuz,
dsx,
Stepanow,
Studebecker,
svartalf).
: (:
yktoo).
.
2018: Python 2 3.
2019: Python 3.8
.