Skip to content

Commit fde404e

Browse files
Added new python releated conceptual example and oops example
1 parent a65f97b commit fde404e

24 files changed

Lines changed: 1297 additions & 114 deletions

.idea/inspectionProfiles/Project_Default.xml

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/inspectionProfiles/profiles_settings.xml

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/workspace.xml

Lines changed: 428 additions & 114 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

accessspecifier/private_example.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# coding=utf-8
2+
class Cup:
3+
def __init__(self, color):
4+
self._color = color # protected variable
5+
self.__content = None # private variable
6+
7+
def fill(self, beverage):
8+
self.__content = beverage
9+
10+
def empty(self):
11+
self.__content = None
12+
13+
def get_content(self):
14+
return self.__content
15+
16+
# By declaring your data member private you mean,
17+
# that nobody should be able to access it from outside the class,
18+
# i.e. strong you can’t touch this policy. Python supports a technique
19+
# called name mangling. This feature turns every member name prefixed
20+
# with at least two underscores and suffixed with at most one underscore into _<className><memberName> .
21+
22+
redCup = Cup("red")
23+
redCup._Cup__content = "tea"
24+
print redCup.get_content()
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# coding=utf-8
2+
class cup:
3+
def __init__(self):
4+
self.color = None
5+
self._content = None # protected variable
6+
7+
def fill(self, beverage):
8+
self._content = beverage
9+
10+
def empty(self):
11+
self._content = None
12+
13+
def get_color(self):
14+
return self.color
15+
16+
def get_content(self):
17+
return self._content
18+
19+
# Protected member is accessible only from within the class and it’s subclasses.
20+
21+
22+
class second_cup():
23+
def content(self, content):
24+
cup()._content = content
25+
print cup().get_content()
26+
27+
cup = cup()
28+
cup._content = "tea"
29+
# print cup.get_content()
30+
print second_cup().content("yes")
31+
32+

jsonexample/__init__.py

Whitespace-only changes.

jsonexample/jsonparseexample.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import json
2+
from collections import namedtuple
3+
4+
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}, "address": {"city": "Ahmedabad",' \
5+
'"pincode": 382345, "country": "india", "state": "gujrat"}, "stock": ["abc", "pqr", "def", "lml"]}'
6+
7+
# list_data = '["abc", "pqr", "def", "lml"]'
8+
9+
# Parse JSON into an object with attributes corresponding to dict keys.
10+
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
11+
12+
# print x.name, x.hometown.name, x.hometown.id, x.address.city
13+
for single_stock_list in x.stock:
14+
pass
15+
# print single_stock_list
16+
17+
18+
# to reuse it # while developing application | webservice
19+
def _json_object_hook(d):
20+
return namedtuple('X', d.keys())(*d.values())
21+
22+
23+
def json2obj(data):
24+
return json.loads(data, object_hook=_json_object_hook)
25+
26+
real_object = json2obj(data)
27+
print real_object.name

ooppython/__init__.py

Whitespace-only changes.

ooppython/battelexample.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# ---------- WARRIORS BATTLE ----------
2+
# We will create a game with this sample output
3+
'''
4+
Sam attacks Paul and deals 9 damage
5+
Paul is down to 10 health
6+
Paul attacks Sam and deals 7 damage
7+
Sam is down to 7 health
8+
Sam attacks Paul and deals 19 damage
9+
Paul is down to -9 health
10+
Paul has Died and Sam is Victorious
11+
Game Over
12+
'''
13+
14+
# We will create a Warrior & Battle class
15+
16+
import random
17+
import math
18+
19+
# Warriors will have names, health, and attack and block maximums
20+
# They will have the capabilities to attack and block random amounts
21+
22+
23+
class Warrior:
24+
def __init__(self, name="warrior", health=0, attkMax=0, blockMax=0):
25+
self.name = name
26+
self.health = health
27+
self.attkMax = attkMax
28+
self.blockMax = blockMax
29+
30+
def attack(self):
31+
# Randomly calculate the attack amount
32+
# random() returns a value from 0.0 to 1.0
33+
attkAmt = self.attkMax * (random.random() + .5)
34+
35+
return attkAmt
36+
37+
def block(self):
38+
39+
# Randomly calculate how much of the attack was blocked
40+
blockAmt = self.blockMax * (random.random() + .5)
41+
42+
return blockAmt
43+
44+
# The Battle class will have the capability to loop until 1 Warrior dies
45+
# The Warriors will each get a turn to attack each turn
46+
47+
48+
class Battle:
49+
50+
def startFight(self, warrior1, warrior2):
51+
52+
# Continue looping until a Warrior dies switching back and
53+
# forth as the Warriors attack each other
54+
while True:
55+
if self.getAttackResult(warrior1, warrior2) == "Game Over":
56+
print("Game Over")
57+
break
58+
59+
if self.getAttackResult(warrior2, warrior1) == "Game Over":
60+
print("Game Over")
61+
break
62+
63+
# A function will receive each Warrior that will attack the other
64+
# Have the attack and block amounts be integers to make the results clean
65+
# Output the results of the fight as it goes
66+
# If a Warrior dies return that result to end the looping in the
67+
# above function
68+
69+
# Make this method static because we don't need to use self
70+
@staticmethod
71+
def getAttackResult(warriorA, warriorB):
72+
warriorAAttkAmt = warriorA.attack()
73+
74+
warriorBBlockAmt = warriorB.block()
75+
76+
damage2WarriorB = math.ceil(warriorAAttkAmt - warriorBBlockAmt)
77+
78+
warriorB.health = warriorB.health - damage2WarriorB
79+
80+
print("{} attacks {} and deals {} damage".format(warriorA.name,
81+
warriorB.name, damage2WarriorB))
82+
83+
print("{} is down to {} health".format(warriorB.name,
84+
warriorB.health))
85+
86+
if warriorB.health <= 0:
87+
print("{} has Died and {} is Victorious".format(warriorB.name,
88+
warriorA.name))
89+
90+
return "Game Over"
91+
else:
92+
return "Fight Again"
93+
94+
95+
def main():
96+
97+
# Create 2 Warriors
98+
paul = Warrior("Paul", 50, 20, 10)
99+
sam = Warrior("Sam", 50, 20, 10)
100+
101+
# Create Battle object
102+
battle = Battle()
103+
104+
# Initiate Battle
105+
battle.startFight(paul, sam)
106+
107+
main()

ooppython/custom_exception.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# ---------- CUSTOM EXCEPTIONS ----------
2+
3+
# Lets trigger an exception if the user enters a
4+
# name that contains a number
5+
6+
# Although you won't commonly create your own exceptions
7+
# this is how you do it
8+
9+
# Create a class that inherits from Exception
10+
class DogNameError(Exception):
11+
def __init__(self, *args, **kwargs):
12+
Exception.__init__(self, *args, **kwargs)
13+
14+
15+
try:
16+
dogName = input("What is your dogs name : ")
17+
18+
if any(char.isdigit() for char in dogName):
19+
# Raise your own exception
20+
# You can raise the built in exceptions as well
21+
raise DogNameError
22+
23+
except DogNameError:
24+
print("Your dogs name can't contain a number")

0 commit comments

Comments
 (0)