我一直在使用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。 –