473,287 Members | 1,580 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Bring object 'out of' Class?

Hello,

I'm currently on the class section of my self-taught journey and have a
question about classes: is it possible to bring a object created
inside the class definitions outside the class so it can be accessed in
the interpreter?

For example, right now I'm working (within Allen Downey's Python
Programmer book) with creating a 'hand' of cards. I want to be able to
deal to 'x' amount of cards to 'x' amount of hands and then be able to
manipulate those hands afterwards. I'm not sure if even what I'm
asking is possible or if I'm getting ahead of myself.

As always, thanks for all your help. My learning is greatly enhanced
with everyone's input on this board. Please feel free to
comment/critique the code...

Here is the section of code that deals hands (but doesn't do anything
past that):

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'

and here is the all of the code:

#!/usr/bin/env python

import random

class Card:
"""represents a playing card
attributes: rank, suit"""

def __init__(self, suit=0, rank=3):
self.suit = suit
self.rank = rank

suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_names = [None, "Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"]

def __str__(self):
#prints card in format: Rank 'of' Suit#
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])

def __cmp__(self, other):
#evaluates which card is ranked higher by suit/rank
#arbitrary definition. depends on the card game
card1 = self.suit, self.rank
card2 = other.suit, other.rank
return cmp(card1, card2)
class Deck:
"""represents a deck of cards. 52 card, 4 suits, 13 cards/suit"""

def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)

def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)

def pop_card(self):
'''removes a card and returns it to another object'''
return self.cards.pop()

def add_cards(self, card):
#adds a card to an object
return self.cards.append(card)

def shuffle(self):
'''must import random, shuffles the deck'''
random.shuffle(self.cards)

def sort_deck(self):
self.cards.sort()

def deal(self, hand, num):
'''moves cards from one object to another'''
for i in range(num):
hand.add_cards(self.pop_card())

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'


class Hand(Deck):
"""child class of Deck. Represents a hand of cards"""

def __init__(self, label=" "):
self.cards = []
self.label = label

Jun 1 '08 #1
3 1691
dave <sq*************@1ya2hoo3.netwrites:
Hello,

I'm currently on the class section of my self-taught journey and have
a question about classes: is it possible to bring a object created
inside the class definitions outside the class so it can be accessed
in the interpreter?

For example, right now I'm working (within Allen Downey's Python
Programmer book) with creating a 'hand' of cards. I want to be able
to deal to 'x' amount of cards to 'x' amount of hands and then be able
to manipulate those hands afterwards. I'm not sure if even what I'm
asking is possible or if I'm getting ahead of myself.

As always, thanks for all your help. My learning is greatly enhanced
with everyone's input on this board. Please feel free to
comment/critique the code...

Here is the section of code that deals hands (but doesn't do anything
past that):

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
You need to use a 'return' statement:

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
hands = []
for i in range(num_of_hands):
newhand = Hand('hand%d' % i)
self.deal(newhand, num)
hands.append(newhand)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
return Hand
Then you can write:
>>hands = deck.deal_cards(4, 5) # On fait une belotte?
And I don't see the need of defining 'Hand' inside 'Deck'.

HTH

--
Arnaud
Jun 1 '08 #2
On 6/1/08, Arnaud Delobelle <ar*****@googlemail.comwrote:
dave <sq*************@1ya2hoo3.netwrites:
[..]
>
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
>


You need to use a 'return' statement:
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''

hands = []

for i in range(num_of_hands):

newhand = Hand('hand%d' % i)
self.deal(newhand, num)
hands.append(newhand)

print '::::%s::::' % (handname.label), '\n', handname, '\n'

return Hand
Should be: return hands
>

Then you can write:
>>hands = deck.deal_cards(4, 5) # On fait une belotte?
[...]
Jun 1 '08 #3
Then you can write:
>
>>>hands = deck.deal_cards(4, 5) # On fait une belotte?

And I don't see the need of defining 'Hand' inside 'Deck'.

HTH
Thanks for the input.

I believe using 'class Hand(Deck):' is to illustrate (in the book)
inheritance and how it can be used. By using 'Hand(Deck)' I can then
use the methods (pop_card, add_cards, etc..) defined in the 'Deck'
class.
Jun 1 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Programmer | last post by:
Hi All Here is my problem I'm using a SQLDataAdapter and DataSet I use the method FillSchema(myDataset, SchemaType.Source) The problem is that when i Check the default Values of the Dataset...
1
by: Bo Xu | last post by:
Object of Combination By Bo Xu Introduction A combination of n things, taken s at a time, often referred as an s-combination out of n, is a way to select a subset of size s from a given set of...
6
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a...
4
by: Davids | last post by:
in my small hangman web project I have a Hangman class which has some methods and properties (int GuessAttempts, string GuessedLetters etc..) which change as the game goes on... Best of all would...
6
by: Paolo Pignatelli | last post by:
I have an aspx code behind page that goes something like this in the HTML view: <asp:HyperLink id=HyperLink1 runat="server" NavigateUrl='<%#"mailto:" &amp;...
9
by: DraguVaso | last post by:
Hi, I want my application to bring another application to the Front. I thought best way to do this was by the Process-model: Dim c As Process = Process.GetCurrentProcess() Dim p As Process...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
8
by: Radx | last post by:
Here in my web application, I have a data entry page with serval controls. Some of the controls have autopostback is set true. But the problem is when two or more people are entering data at the...
3
by: dave | last post by:
Hello, I'm currently on the class section of my self-taught journey and have a question about classes: is it possible to bring a object created inside the class definitions outside the class so...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.