@staticmethoddef 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')
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) # Trueisinstance(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.
class empDetails:def __init__(self,name,sal):self.name=nameself.sal=sal@classmethoddef increment(cls,name,none):return cls('yarramsetti',6000 + 500)@staticmethoddef salChecking(sal):return sal > 6000
emp1=empDetails('durga prasad',6000)emp2=empDetails.increment('yarramsetti',100)# output is 'durga prasad'print emp1.name# output put is 6000print emp1.sal# output is 6500,because it change the sal variableprint emp2.sal# output is 'yarramsetti' it change the state of name variableprint emp2.name# output is True, because ,it change the state of sal variableprint empDetails.salChecking(6500)
class Example(object):
def regular_instance_method(self):"""A function of an instance has access to every attribute of thatinstance, 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)
@classmethoddef 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)
@staticmethoddef a_static_method():"""A static method has no information about instances or classesunless explicitly given. It just lives in the class (and thus itsinstances') namespace."""return some_function_h()
对于实例方法和类方法,不接受至少一个参数是TypeError,但不理解该参数的语义学是用户错误。
(定义some_function,例如:
some_function_h = some_function_g = some_function_f = lambda x=None: x
def an_instance_method(self, arg, kwarg=None):cls = type(self) # Also has the class of instance!...
@classmethoddef a_class_method(cls, arg, kwarg=None):...
@staticmethoddef a_static_method(arg, kwarg=None):...
In [31]: PythonBook.book1()Out[31]: Book: Learning Python, Author: Mark LutzIn [32]: PythonBook.book2()Out[32]: Book: Python Think, Author: Allen B Dowey