如何在Python中创建类(即静态)变量或方法?


当前回答

您可以使用列表或字典来获取实例之间的“静态行为”。

class Fud:

     class_vars = {'origin_open':False}

     def __init__(self, origin = True):
         self.origin = origin
         self.opened = True
         if origin:
             self.class_vars['origin_open'] = True


     def make_another_fud(self):
         ''' Generating another Fud() from the origin instance '''

         return Fud(False)


     def close(self):
         self.opened = False
         if self.origin:
             self.class_vars['origin_open'] = False


fud1 = Fud()
fud2 = fud1.make_another_fud()

print (f"is this the original fud: {fud2.origin}")
print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is this the original fud: False
# is the original fud open: True

fud1.close()

print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is the original fud open: False

其他回答

python中的静态方法称为classmethods。查看以下代码

class MyClass:

    def myInstanceMethod(self):
        print 'output from an instance method'

    @classmethod
    def myStaticMethod(cls):
        print 'output from a static method'

>>> MyClass.myInstanceMethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method myInstanceMethod() must be called [...]

>>> MyClass.myStaticMethod()
output from a static method

注意,当我们调用方法myInstanceMethod时,会得到一个错误。这是因为它要求在此类的实例上调用该方法。方法myStaticMethod使用decorator@classmethod设置为类方法。

为了好玩,我们可以通过传入类的实例来调用类上的myInstanceMethod,如下所示:

>>> MyClass.myInstanceMethod(MyClass())
output from an instance method

关于Python的属性查找,一个非常有趣的点是它可以用来创建“虚拟变量”:

class A(object):

  label="Amazing"

  def __init__(self,d): 
      self.data=d

  def say(self): 
      print("%s %s!"%(self.label,self.data))

class B(A):
  label="Bold"  # overrides A.label

A(5).say()      # Amazing 5!
B(3).say()      # Bold 3!

通常情况下,在创建它们之后,不会有任何分配给它们。请注意,查找使用self,因为尽管标签在不与特定实例关联的意义上是静态的,但值仍然取决于(的类)实例。

当然是的,Python本身没有任何静态数据成员,但我们可以这样做

class A:
    counter =0
    def callme (self):
        A.counter +=1
    def getcount (self):
        return self.counter  
>>> x=A()
>>> y=A()
>>> print(x.getcount())
>>> print(y.getcount())
>>> x.callme() 
>>> print(x.getcount())
>>> print(y.getcount())

输出

0
0
1
1

解释

here object (x) alone increment the counter variable
from 0 to 1 by not object y. But result it as "static counter"

您可以创建类变量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")

我在回答中解释了类变量,在回答中说明了类方法和静态方法,并在回答中介绍了实例方法。

所以这可能是一个黑客,但我一直在使用eval(str)来获取一个静态对象,这有点矛盾,在python 3中。

有一个Records.py文件,除了用保存一些参数的静态方法和构造函数定义的类对象外,它什么都没有。然后从另一个.py文件导入Records,但我需要动态选择每个对象,然后根据读入的数据类型按需实例化它。

因此,在object_name=“RecordOne”或类名的情况下,我调用cur_type=eval(object_name),然后要实例化它,请执行cur_inst=cur_type(args)然而,在实例化之前,您可以从cur_type.getName()调用静态方法,例如,类似于抽象基类实现或任何目标。然而,在后端,它可能是在python中实例化的,并不是真正静态的,因为eval返回一个对象。。。。必须已实例化。。。。这会产生类似静态的行为。