class A(object): def foo(self,x): print("executing foo({}, {})".format(self,x)) @classmethod def class_foo(cls,x): print("executing class_foo({}, {})".format(cls,x)) @staticmethod def static_foo(x): print("executing static_foo({})".format(x)) a = A()
self
foo
is bound to the object a
, class A
a.foo(1)
executing foo(<__main__.A object at 0x10f0a8550>, 1)
a.foo
<bound method A.foo of <__main__.A object at 0x10f0a8550>>
A.class_foo(1)
class_foo
is bound to the class A
A.class_foo(1)
executing class_foo(<class '__main__.A'>, 1)
A.class_foo
<bound method type.class_foo of <class '__main__.A'>>
a.class_foo(1)
executing class_foo(<class '__main__.A'>, 1)
a.static_foo(1)
executing static_foo(1)
A.static_foo('hi')
executing static_foo(hi)
datetime
or pytz
module)
class Date(object): def __init__(self, year=0, month=0, day=0): self.day = day self.month = month self.year = year def __repr__(self): return "It's the {}.{}.{}".format(self.day, self.month, self.year)
Date(2014, 4, 1)
It's the 1.4.2014
yyyy-mm-dd
string_date = '01-04-2014' day, month, year = map(int, string_date.split('-')) date1 = Date(year, month, day) date1
>>> >>> It's the 1.4.2014
class Date(object): def __init__(self, year=0, month=0, day=0): self.day = day self.month = month self.year = year def __repr__(self): return "It's the {}.{}.{}".format(self.day, self.month, self.year) @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) date1 = cls(year, month, day) return date1
cls
object (of class 'type') holds the class itself
All children of Date
will have from_string
Date.from_string('01-04-2014')
It's the 1.4.2014
Date
class
Date
class too
date_as_string = '01-04-2014' day, month, year = map(int, date_as_string.split('-')) day <= 31 and month <= 12 and year <= 3999
>>> True
class Date(object): def __init__(self, year=0, month=0, day=0): self.day = day self.month = month self.year = year def __repr__(self): return "It's the {}.{}.{}".format(self.day, self.month, self.year) @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
Date
cls
or self
objects, makes that explicit
All children of Date
will have is_valid_string
Date.is_date_valid('01-04-2014')
True
A.foo
is just a function, expects 2 arguments
a.foo
has object a
bound as first argument
a.class_foo
, class A
is bound to class_foo
via object a
a.static_foo
just returns function with no arguments bound
A.foo
<function A.foo at 0x10f082a70>
a.foo
<bound method A.foo of <__main__.A object at 0x10f0a8550>>
a.class_foo
<bound method type.class_foo of <class '__main__.A'>>
a.static_foo
<function A.static_foo at 0x10f082b90>
self
as first argument
self
object must be of same class
A.foo
unbound method
A.foo
simple function, can be bound