logo codesdope

Subclass in Python


By the name of the topic, it is clear in itself that we are going to deal with the subclass of any class. To give you a general idea, think that square is also a rectangle, which means that it is a subclass of rectangle.
Let's make it clearer.
Suppose we define a rectangle with some length and breadth. Now, square is also a rectangle but having the same length and breadth.

subclass in python

I think, it has given you the feel that square can be a subclass of rectangle.

Instead of writing new data members' methods, one can inherit the members of an existing class. This existing class is called the base class or superclass, and the new class is called the derived class or sub-class.

Let's learn to do all these things in Python.

class Child():
	def __init__(self,name):
		self.name = name
class Student(Child):
	def __init__(self,name,roll):
		self.roll = roll
		Child.__init__(self,name)
a = Child("xyz")
print a.name
b = Student("abc",12)
print b.name
print b.roll
Output
xyz
abc
12

Most of the codes must be clear. Let me make it clearer.
class Student(Child) : It means that 'Student' is a class which is inherited from the 'Child' class. In simple words, it's a subclass of 'Child' class.
Now, 'Student' class has its own initializer, which means that we have to pass name and roll while creating its object.
Child.__init__(self,name) : It initializes the superclass (parent class) 'Child' and passes the 'name'.

If we wouldn't have an initializer in the Student class, it would have used its Child's initializer and we would have made objects by just passing the 'name'(a parameter). An example is given below
class Child():
	def __init__(self,name):
		self.name = name
class Student(Child):
	pass
a = Child("xyz")
print a.name
b = Student("abc")
print b.name
Output
xyz
abc

Square and rectangle example

class Rectangle():
	def __init__(self,leng,br):
		self.length = leng
		self.breadth = br
	'''while calling a method in a class python 
	automatically passes an instance( object ) of it.
	so we have to pass sef in area i.e. area(self)'''
	def area(self):
		'''length and breadth are not globally defined.
		So, we have to access them as self.length'''
		return self.length*self.breadth
class Square(Rectangle):
	def __init__(self,side):
		Rectangle.__init__(self,side,side)
		self.side = side
s = Square(4)
print s.length
print s.breadth
print s.side
print s.area()# It appears as nothing is passed but python will pass an instance of class.
Output
4
4
4
16

There is nothing new in the above code to explain. If you are facing any difficulty, then read the comments inside the code.
You can ask questions in the discussion section anytime and feel free to ask.

Let's make a playing card game


Rules of the game :
1. First player will select a card.
2. Now the second player will select a card.
3. If the second player selects a card of the same value as selected by the first player, he will get points.
4. Now the second player will first select a card and then the first player
5. If the first player selects a card of the same value as selected by second player then he will get points.
6. Repeat steps 1 to 5.
7. Player with more score will win the game.

import os#for screen clear
import random#for shuffling
import getpass#for invisible input

#screen clear
os.system('clear')

class Card:
	def __init__(self,suite,value):
		self.suite = suite
		self.value = value
			

#suites
suites = ["diamond","spade","heart","club"]

#values of card
values = ["A","2","3","4","5","6","7","8","9","10","K","Q","J"]

#list to store cards
cards = []

#making cards
for suite in suites:
	for value in values:
		x = Card(suite,value)
		cards.append(x)

#shuffling cards
random.shuffle(cards)

#empty list of cards for both players
player1_cards=[]
player2_cards=[]

#distributing cards among players
for i in range(0,52):
	if i<26:
		player1_cards.append(cards[i])
	else:
		player2_cards.append(cards[i])

no_of_cards = 52

#function to cards of each player
#'\t' is tabspace character. It will print one tabspace. Similarly '\n' is newline character. It will print a new line
def print_cards():
	print "Player 1 has :\t\t\tPlayer 2 has:"
	for i in range(0,no_of_cards/2):
		print str(player1_cards[i].value)+"\t"+str(player1_cards[i].suite)+"\t\t\t"+str(player2_cards[i].value)+"\t"+str(player2_cards[i].suite)

print_cards()

#score of player 1 and 2
p1_score = 0
p2_score = 0


#gameplay
for i in range(0,no_of_cards):
	if i%2 == 0:#player 1 will choose first

		while True:		

			#getpass for invisible input
			x1 = getpass.getpass("\nPlayer 1 : Enter value and type ENTER and then enter type of card\n")
			y1 = getpass.getpass("")

			#to check entered correct or not
			correct1 = 0

			#checking if entered card is in cards of player 1 or not
			for j in player1_cards:
				if j.suite == y1 and j.value == x1:

					#deleteing entered card
					del(player1_cards[player1_cards.index(j)])
					correct1 = correct1+1

					#now number of cards is 1 less
					no_of_cards = no_of_cards-1

			if correct1==0:
				print "ENTER CORRECT CARD"
			else:
				#Correct card is entered. So, break while
				break;

		while True:

			x2 = getpass.getpass("\nPlayer 2 : Enter value and type ENTER and then enter type of card\n")
			y2 = getpass.getpass("")

			#to check entered card is correct or not
			correct2 = 0

		#checking if entered card is in cards of player 1 or not
			for j in player2_cards:
				if j.suite == y2 and j.value == x2:

					#deleteing entered card
					del(player2_cards[player2_cards.index(j)])
					correct2 = correct2+1

					#now number of cards is 1 less
					no_of_cards = no_of_cards-1

			if correct2==0:
				print "ENTER CORRECT CARD"
			else:
				#Correct card is entered
				break

		#checking if value both both cards matches or not
		if x1==x2:
			p2_score=p2_score+10

	else:#player 2 will choose first

		while True:		

			x2 = getpass.getpass("\nPlayer 2 : Enter value and type ENTER and then enter type of card\n")
			y2 = getpass.getpass("")

			#to check entered correct or not
			correct2 = 0

			#checking if entered card is in cards of player 1 or not
			for j in player2_cards:
				if j.suite == y2 and j.value == x2:

					#deleteing entered card
					del(player2_cards[player2_cards.index(j)])
					correct2 = correct2+1

					#now number of cards is 1 less
					no_of_cards = no_of_cards-1

			if correct2==0:
				print "ENTER CORRECT CARD"
			else:
				#Correct card is entered. So, break while
				break;

		while True:

			x1 = getpass.getpass("\nPlayer 1 : Enter value and type ENTER and then enter type of card\n")
			y1 =getpass.getpass("")

			#to check entered card is correct or not
			correct1 = 0

		#checking if entered card is in cards of player 1 or not
			for j in player1_cards:
				if j.suite == y1 and j.value == x1:

					#deleteing entered card
					del(player1_cards[player1_cards.index(j)])
					correct1 = correct1+1

					#now number of cards is 1 less
					no_of_cards = no_of_cards-1

			if correct1==0:
				print "ENTER CORRECT CARD"
			else:
				#Correct card is entered
				break

		#checking if value both both cards matches or not
		if x1==x2:
			p1_score=p1_score+10
	print_cards()
	print "Player1 score :",p1_score,"Player2 score :",p2_score


if p1_score>p2_score:
	print "PLAYER 1 WINS"
elif p2score>p1score:
	print "PLAYER 2 WINS"
else:
	print "MATCH DRAWS"
Are real games made like this?
Yes, we have just made the structure of a game to link it to graphics. You can expand your knowledge after completing this course.
Make this better.
Ask user for the number of players, give bonus points for some situations or implement any other idea that you have.

Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
-Michael Dell


Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.