2016-06-07 63 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语句)他们有任何影响之前,必须执行。 (您 可以想见,在放置的,如果 声明,或内部的功能一个分支类的定义。)

正如你可以看到,这些表达式求值,你甚至可以“如果”语句中使用。