我一直在使用PHP一段時間,剛開始使用Python。在學習時我遇到了Python中的一個特性。Python如何將表達式分配給對象屬性?
在Python
class A:
#some class Properties
class B:
a = A() # assiging an expression to the class Property is possible with python.
在PHP
class A{
}
class B{
$a = new A(); // PHP does not allow me to do this.
// I need to do this instead.
function __construct(){
$this->a = new A();
}
}
我想知道這是爲什麼。 python如何以不同的方式來代碼,如果有什麼辦法可以用PHP來完成。
「爲什麼」的答案是「因爲它們是完全不同的語言。」如果你一直在使用PHP一段時間,你可能已經知道正確的PHP方法來做到這一點。在另一種語言中寫一種語言永遠不會有好結果 – TigerhawkT3
在python解釋語言的情況下,它會進入基於級別的範圍,試圖分析什麼在找到函數範圍時必須進行初始化。 –
這有點類似於PHP中的[static](http://php.net/manual/en/language.oop5.static.php)類變量。請參閱http://stackoverflow.com/questions/68645/static-class-variables-in-python。 –