我已经使用PHP一段时间了,刚开始使用Python。 我在学习时遇到了Python中的一个功能。
在蟒蛇中
class A:
#some class Properties
class B:
a = A() # assiging an expression to the class Property is possible with python.
在菲律宾比索
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 做到这一点。
in 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
有关 python 静态和对象属性的更多阅读
在 PHP 中
在PHP中,单例模式使用静态变量的概念在对象之间共享实例。
希望这能澄清类属性和对象属性。
我相信这是特定于语言的事情。从文档中
class ClassName: <statement-1> . . . <statement-N>
类定义,如函数定义(def 语句),必须先执行,然后才能产生任何效果。(你 可以想象将类定义放在 if 的分支中 语句,或在函数内。
如您所见,这些表达式被计算,您甚至可以使用"if"语句。