python - Sens de @classmethod et @staticmethod pour débutant

Mots clés : pythonoopstatic-methodsclass-method

meilleur 3 Réponses python - Sens de @classmethod et @staticmethod pour débutant

vote vote

92

class Date(object):      def __init__(self, day=0, month=0, year=0):         self.day = day         self.month = month         self.year = year      @classmethod     def from_string(cls, date_as_string):         day, month, year = map(int, date_as_string.split('-'))         date1 = cls(day, month, year)         return date1      @staticmethod     def is_date_valid(date_as_string):         day, month, year = map(int, date_as_string.split('-'))         return day <= 31 and month <= 12 and year <= 3999  date2 = Date.from_string('11-09-2012') is_date = Date.is_date_valid('11-09-2012') 
class Date(object):      def __init__(self, day=0, month=0, year=0):         self.day = day         self.month = month         self.year = year 
day, month, year = map(int, string_date.split('-')) date1 = Date(day, month, year) 
    @classmethod     def from_string(cls, date_as_string):         day, month, year = map(int, date_as_string.split('-'))         date1 = cls(day, month, year)         return date1  date2 = Date.from_string('11-09-2012') 
    @staticmethod     def is_date_valid(date_as_string):         day, month, year = map(int, date_as_string.split('-'))         return day <= 31 and month <= 12 and year <= 3999      # usage:     is_date = Date.is_date_valid('11-09-2012') 
vote vote

82

class Date:   def __init__(self, month, day, year):     self.month = month     self.day   = day     self.year  = year     def display(self):     return "{0}-{1}-{2}".format(self.month, self.day, self.year)     @staticmethod   def millenium(month, day):     return Date(month, day, 2000)  new_year = Date(1, 1, 2013)               # Creates a new Date object millenium_new_year = Date.millenium(1, 1) # also creates a Date object.   # Proof: new_year.display()           # "1-1-2013" millenium_new_year.display() # "1-1-2000"  isinstance(new_year, Date) # True isinstance(millenium_new_year, Date) # True 
class DateTime(Date):   def display(self):       return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)   datetime1 = DateTime(10, 10, 1990) datetime2 = DateTime.millenium(10, 10)  isinstance(datetime1, DateTime) # True isinstance(datetime2, DateTime) # False  datetime1.display() # returns "10-10-1990 - 00:00:00PM" datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details. 
@classmethod def millenium(cls, month, day):     return cls(month, day, 2000) 
datetime1 = DateTime(10, 10, 1990) datetime2 = DateTime.millenium(10, 10)  isinstance(datetime1, DateTime) # True isinstance(datetime2, DateTime) # True   datetime1.display() # "10-10-1990 - 00:00:00PM" datetime2.display() # "10-10-2000 - 00:00:00PM" 
vote vote

75

class Example(object):      def regular_instance_method(self):         """A function of an instance has access to every attribute of that          instance, including its class (and its attributes.)         Not accepting at least one argument is a TypeError.         Not understanding the semantics of that argument is a user error.         """         return some_function_f(self)      @classmethod     def a_class_method(cls):         """A function of a class has access to every attribute of the class.         Not accepting at least one argument is a TypeError.         Not understanding the semantics of that argument is a user error.         """         return some_function_g(cls)      @staticmethod     def a_static_method():         """A static method has no information about instances or classes         unless explicitly given. It just lives in the class (and thus its          instances') namespace.         """         return some_function_h() 
some_function_h = some_function_g = some_function_f = lambda x=None: x 
instance = Example() instance.regular_instance_method  
instance.regular_instance_method() 
>>> instance = Example() >>> instance.regular_instance_method() <__main__.Example object at 0x00000000399524E0> 
>>> instance.a_class_method() <class '__main__.Example'> >>> Example.a_class_method() <class '__main__.Example'> 
>>> print(instance.a_static_method()) None 
def function(x, y, z): ... 
def function(y, z): ... 
def function(z): ... 
def an_instance_method(self, arg, kwarg=None):     cls = type(self)             # Also has the class of instance!     ...  @classmethod def a_class_method(cls, arg, kwarg=None):     ...  @staticmethod def a_static_method(arg, kwarg=None):     ... 
>>> 'abc'.translate(str.maketrans({'a': 'b'})) 'bbc' 
>>> dict.fromkeys('abc') {'a': None, 'c': None, 'b': None} 
>>> class MyDict(dict): pass >>> type(MyDict.fromkeys('abc')) <class '__main__.MyDict'>  

Questions similaires