Méthodes statiques en Python

Mots clés : pythonstatic-methodspython

meilleur 4 Réponses Méthodes statiques en Python

vote vote

98

class MyClass(object):     @staticmethod     def the_static_method(x):         print(x)  MyClass.the_static_method(2)  # outputs 2 
class MyClass(object):     def the_static_method(x):         print(x)     the_static_method = staticmethod(the_static_method)  MyClass.the_static_method(2)  # outputs 2 
class C:     @staticmethod     def f(arg1, arg2, ...): ... 
vote vote

80

class Dog:     count = 0 # this is a class variable     dogs = [] # this is a class variable      def __init__(self, name):         self.name = name #self.name is an instance variable         Dog.count += 1         Dog.dogs.append(name)      def bark(self, n): # this is an instance method         print("{} says: {}".format(self.name, "woof! " * n))      def rollCall(n): #this is implicitly a class method (see comments below)         print("There are {} dogs.".format(Dog.count))         if n >= len(Dog.dogs) or n < 0:             print("They are:")             for dog in Dog.dogs:                 print("  {}".format(dog))         else:             print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))  fido = Dog("Fido") fido.bark(3) Dog.rollCall(-1) rex = Dog("Rex") Dog.rollCall(0) 
rex.rollCall(-1) 
@staticmethod 
rex.rollCall(-1) 
class Dog:     count = 0 # this is a class variable     dogs = [] # this is a class variable      def __init__(self, name):         self.name = name #self.name is an instance variable         Dog.count += 1         Dog.dogs.append(name)      def bark(self, n): # this is an instance method         print("{} says: {}".format(self.name, "woof! " * n))      @staticmethod     def rollCall(n):         print("There are {} dogs.".format(Dog.count))         if n >= len(Dog.dogs) or n < 0:             print("They are:")             for dog in Dog.dogs:                 print("  {}".format(dog))         else:             print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))   fido = Dog("Fido") fido.bark(3) Dog.rollCall(-1) rex = Dog("Rex") Dog.rollCall(0) rex.rollCall(-1) 
vote vote

74

>>> class C: ...     @staticmethod ...     def hello(): ...             print "Hello World" ... >>> C.hello() Hello World 
vote vote

65

ClassName.StaticMethod() 
class ClassName(object):      @staticmethod     def static_method(kwarg1=None):         '''return a value that is a function of kwarg1''' 
class ClassName(object):      def static_method(kwarg1=None):         '''return a value that is a function of kwarg1'''      static_method = staticmethod(static_method) 
ClassName.static_method() 
class ClassName(object):      @classmethod     def class_method(cls, kwarg1=None):         '''return a value that is a function of the class and kwarg1''' 
new_instance = ClassName.class_method() 
new_dict = dict.fromkeys(['key1', 'key2']) 

Questions similaires