如何在Python中创建类(即静态)变量或方法?
当前回答
当在任何成员方法之外定义某个成员变量时,该变量可以是静态的,也可以是非静态的,具体取决于该变量的表达方式。
CLASSNAME.var是静态变量INSTANCENAME.var不是静态变量。类内部的self.var不是静态变量。未定义类成员函数内的var。
例如:
#!/usr/bin/python
class A:
var=1
def printvar(self):
print "self.var is %d" % self.var
print "A.var is %d" % A.var
a = A()
a.var = 2
a.printvar()
A.var = 3
a.printvar()
结果是
self.var is 2
A.var is 1
self.var is 2
A.var is 3
其他回答
关于静态财产和实例财产,需要注意一件特殊的事情,如下例所示:
class my_cls:
my_prop = 0
#static property
print my_cls.my_prop #--> 0
#assign value to static property
my_cls.my_prop = 1
print my_cls.my_prop #--> 1
#access static property thru' instance
my_inst = my_cls()
print my_inst.my_prop #--> 1
#instance property is different from static property
#after being assigned a value
my_inst.my_prop = 2
print my_cls.my_prop #--> 1
print my_inst.my_prop #--> 2
这意味着在将值分配给实例属性之前,如果我们试图通过“实例”访问属性,则使用静态值。python类中声明的每个属性在内存中总是有一个静态槽。
在类定义中声明但不在方法中声明的变量是类或静态变量:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
正如@millerdev所指出的,这会创建一个类级别i变量,但这与任何实例级别i变量都不同,因此您可以
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
这与C++和Java不同,但与C#没有太大区别,在C#中,不能使用对实例的引用来访问静态成员。
看看Python教程对类和类对象的主题有什么看法。
@Steve Johnson已经回答了静态方法的问题,也在Python库参考中的“内置函数”中进行了说明。
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy推荐classmethods而不是staticmethod,因为该方法随后会接收类类型作为第一个参数。
您可以创建类变量x、实例变量名、实例方法test1(self)、类方法test2(cls)和静态方法test3(),如下所示:
class Person:
x = "Hello" # Class variable
def __init__(self, name):
self.name = name # Instance variable
def test1(self): # Instance method
print("Test1")
@classmethod
def test2(cls): # Class method
print("Test2")
@staticmethod
def test3(): # Static method
print("Test3")
我在回答中解释了类变量,在回答中说明了类方法和静态方法,并在回答中介绍了实例方法。
您还可以使用元类强制类为静态类。
class StaticClassError(Exception):
pass
class StaticClass:
__metaclass__ = abc.ABCMeta
def __new__(cls, *args, **kw):
raise StaticClassError("%s is a static class and cannot be initiated."
% cls)
class MyClass(StaticClass):
a = 1
b = 3
@staticmethod
def add(x, y):
return x+y
然后,每当您意外尝试初始化MyClass时,都会收到StaticClassError。
我发现最好的方法是使用另一个类。您可以创建一个对象,然后将其用于其他对象。
class staticFlag:
def __init__(self):
self.__success = False
def isSuccess(self):
return self.__success
def succeed(self):
self.__success = True
class tryIt:
def __init__(self, staticFlag):
self.isSuccess = staticFlag.isSuccess
self.succeed = staticFlag.succeed
tryArr = []
flag = staticFlag()
for i in range(10):
tryArr.append(tryIt(flag))
if i == 5:
tryArr[i].succeed()
print tryArr[i].isSuccess()
通过上面的示例,我创建了一个名为staticFlag的类。
此类应显示静态变量__success(私有静态变量)。
tryIt类表示我们需要使用的常规类。
现在我为一个标志(staticFlag)创建了一个对象。此标志将作为对所有常规对象的引用发送。
所有这些对象都被添加到列表tryArr中。
此脚本结果:
False
False
False
False
False
True
True
True
True
True
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字