Skip to content

Commit 424a013

Browse files
@Class, @static methods added
1 parent 694e7c7 commit 424a013

File tree

4 files changed

+169
-0
lines changed

4 files changed

+169
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
2+
3+
# Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities:
4+
# "classmethod must have a reference to a class object as the first parameter"
5+
6+
7+
# whereas staticmethod can have no parameters at all.
8+
9+
10+
class Date(object):
11+
12+
def __init__(self, day=0, month=0, year=0):
13+
self.day = day
14+
self.month = month
15+
self.year = year
16+
17+
# let's look more carefully at the above implementation, and review what advantages we have here:
18+
# We've implemented date string parsing in one place and it's reusable now.
19+
# Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits
20+
# the OOP paradigm far better).
21+
# cls is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all
22+
# children will have from_string defined also.
23+
24+
@classmethod
25+
def from_string(cls, date_as_string):
26+
day, month, year = map(int, date_as_string.split('-'))
27+
date1 = cls(day, month, year) #cls is an object that holds the class itself,
28+
return date1
29+
30+
@staticmethod
31+
def is_date_valid(date_as_string):
32+
day, month, year = map(int, date_as_string.split('-'))
33+
return day <= 31 and month <= 12 and year <= 3999 #This task is also logically bound to the Date class we've used so far, but doesn't require instantiation of it.
34+
35+
36+
# print Date.from_string('11-09-2012').is_date_valid('11-09-2012')
37+
# print Date.is_date_valid('11-09-2012')
38+
39+
# So, as we can see from usage of staticmethod, we don't have any access to what the class is---it's basically just a function, called
40+
# syntactically like a method.
41+
# but without access to the object and its internals (fields and another methods), while classmethod does.
42+
43+
# class_instance = Date()
44+
# print class_instance.day
45+
46+
47+
48+
49+
# I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating additional
50+
# constructor.
51+
52+
53+
# In the example above, we have used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable
54+
# parameters. The same can be done with @staticmethod as is shown in the code below
55+
56+
57+
# @staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This
58+
# means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not
59+
# use the instance).
60+
61+
62+
# @classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we n
63+
# normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
64+
65+
66+
67+
# Conclusion :: @staticmethod function is nothing more than a function defined inside a class.
68+
69+
70+
# USE CASE 2:
71+
72+
73+
class Date(object): # superclass
74+
def __init__(self, month, day, year):
75+
self.month = month
76+
self.day = day
77+
self.year = year
78+
79+
80+
def display(self):
81+
return "{0}-{1}-{2}".format(self.month, self.day, self.year)
82+
83+
84+
@staticmethod
85+
def millenium(month, day):
86+
return Date(month, day, 2000)
87+
88+
# @classmethod
89+
# def millenium(cls,month, day):
90+
# return cls(month, day, 2000) Got it ;)
91+
92+
new_year = Date(1, 1, 2013) # Creates a new Date object
93+
millenium_new_year = Date.millenium(1, 1) # also creates a Date object.
94+
95+
# Proof:
96+
new_year.display() # "1-1-2013"
97+
millenium_new_year.display() # "1-1-2000"
98+
99+
isinstance(new_year, Date) # True
100+
isinstance(millenium_new_year, Date) # True
101+
102+
103+
class DateTime(Date): # subclass
104+
def display(self):
105+
return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)
106+
107+
108+
datetime1 = DateTime(10, 10, 1990)
109+
datetime2 = DateTime.millenium(10, 10)
110+
111+
print isinstance(datetime1, DateTime) # True
112+
print isinstance(datetime2, DateTime) # False
113+
114+
# @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via i
115+
# nheritance, can be overridden by subclass. That’s because the first argument for @classmethod function must always be cls (class).
116+
117+
# Factory methods, that are used to create an instance for a class using for example some sort of pre-processing.
118+
119+

filter_in_python.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
# filter(function_object, iterable)
3+
4+
# Like map function, filter function also returns a list of element. Unlike map function filter function can only have one iterable as input.
5+
6+
even_ = [2,3,4,5,6,7,8]
7+
8+
print map(lambda x: x % 2 == 0,even_)
9+
print filter(lambda x: x % 2 == 0,even_)
10+
11+
dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
12+
13+
print filter(lambda x: x['name'] == 'python', dict_a)

map_in_python.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88
def multiply(x):
99
return x + x
1010

11+
def int_fn(x):
12+
return x
1113

14+
print map(int_fn, [9,9])
1215
print map(multiply, [1,2,3,4])
1316

1417
print map(lambda x : x*x, [1,2,3,4])

subclass_in_python.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
3+
4+
# A Python program to demonstrate inheritance
5+
6+
# Base or Super class. Note object in bracket.
7+
class Person(object):
8+
9+
# Constructor
10+
def __init__(self, name):
11+
self.name = name
12+
13+
# To get name
14+
def getName(self):
15+
return self.name
16+
17+
# To check if this person is employee
18+
def isEmployee(self):
19+
return False
20+
21+
22+
# Inherited or Sub class (Note Person in bracket)
23+
class Employee(Person):
24+
25+
# Here we return true
26+
def isEmployee(self):
27+
return True
28+
29+
# Driver code
30+
emp = Person("Geek1") # An Object of Person
31+
print(emp.getName(), emp.isEmployee())
32+
33+
emp = Employee("Geek2") # An Object of Employee
34+
print(emp.getName(), emp.isEmployee())

0 commit comments

Comments
 (0)