2016-06-07 95 views
0

我一直在使用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來完成。

+0

「爲什麼」的答案是「因爲它們是完全不同的語言。」如果你一直在使用PHP一段時間,你可能已經知道正確的PHP方法來做到這一點。在另一種語言中寫一種語言永遠不會有好結果 – TigerhawkT3

+0

在python解釋語言的情況下,它會進入基於級別的範圍,試圖分析什麼在找到函數範圍時必須進行初始化。 –

+0

這有點類似於PHP中的[static](http://php.net/manual/en/language.oop5.static.php)類變量。請參閱http://stackoverflow.com/questions/68645/static-class-variables-in-python。 –

回答

2

在Python的類定義中聲明

class A: 
    #some class Properties 

class B: 
    a = A() # assigning to the class Property 
    # class properties are shared across all instances of class B 
    # this is a static property 

類的構造函數內聲明的變量

變量

class A: 
    #some class Properties 

class B: 
    def __init__(self): 
     self.a = A() # assigning to the object Property 
     # this property is private to this object 
     # this is a instance property 

多看書對蟒蛇static and object attributes

in PHP

inPHP,singleton pattern使用靜態變量的概念在對象之間共享實例。

希望澄清有關類屬性和對象屬性。

0

我相信這是語言特定的事情。從docs

class ClassName: 
    <statement-1> 
    . 
    . 
    . 
    <statement-N> 

類定義,就像函數定義(DEF語句)他們有任何影響之前,必須執行。 (您 可以想見,在放置的,如果 聲明,或內部的功能一個分支類的定義。)

正如你可以看到,這些表達式求值,你甚至可以「如果」語句中使用。

相關問題