473,698 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assigning values in __init__

Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?

I'm trying to think ahead to when I might want to add new attributes,
and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.

Or maybe there's some way to loop through two lists (the stats and the
attributes) and assign them that way? I was thinking of a nested for
statement but that didn't seem to work.
Nov 6 '06 #1
16 1934
John Salerno wrote:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?

I'm trying to think ahead to when I might want to add new attributes,
and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.

Or maybe there's some way to loop through two lists (the stats and the
attributes) and assign them that way? I was thinking of a nested for
statement but that didn't seem to work.
Sounds like what you should be doing is something like keyword arguments
instead.

class Character(objec t):
def __init__(self, name, **kwargs):
self.name=name
for key, value in kwargs.items():
setattr(self, key, value)
z=Character('na me', strength=10, dexterity=5, intelligence=3, luck=0)

Now you can easily introduce new keyword arguments.

-Larry
Nov 6 '06 #2

John Salerno wrote:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?
How about:

class Character(objec t):

def __init__(self, name, **kwargs):
self.name = name
self.__dict__.u pdate(kwargs)

c = Character( "Plato", strength=10, luck=12)

print getattr(c, "strength")
print getattr(c, "luck")

10
12

Nov 6 '06 #3
John Salerno wrote:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?

I'm trying to think ahead to when I might want to add new attributes,
and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.

Or maybe there's some way to loop through two lists (the stats and the
attributes) and assign them that way? I was thinking of a nested for
statement but that didn't seem to work.
If your program deals with 4-element tuples then although you *could*
use *stats in your calls to pass each element of the tuple as a single
argument, that's not really necessary. A way to write the
initializations you want without using indexing is:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength, self.dexterity, \
self.intelligen ce, self.luck = stats

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Nov 7 '06 #4
On Mon, 06 Nov 2006 16:57:58 -0500, John Salerno wrote:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?

Whenever possible, think about writing self-documenting code:

def __init__(self, name, strength, dexterity, intelligence, luck):
self.name = name
self.strength = strength
# etc.

seems perfectly acceptable to me (if a tad verbose, but that isn't a big
deal -- write once, never touch again).

The problem with function signatures like these:

def __init__(self, name, stats):
def __init__(self, name, *stats):

is that the format of stats is left unstated. Is it (luck, strength,
intelligence) or (strength, intelligence, luck) or (wisdom, charisma,
power, health) or something else? You shouldn't need to read the code
line by line to find out, and relying on documentation risks having the
code and docs get out of sync.

If you expect the stats to be passed as a single tuple, you can still make
it explicit: just wrap the field names within brackets.

def __init__(self, name, (strength, dexterity, intelligence, luck) ):
I'm trying to think ahead to when I might want to add new attributes,
If this is likely, you could do something like this:

def __init__(self, name, **stats):
self.name = name
self.__dict__.u pdate(stats)

Adding extra attributes is fine, since they will just be ignored, but what
if the caller adds an attribute "itnelligen ce" (instead of intelligence)?
You're now writing lots of code like this:

def save_intelligen ce(self, threshold):
"""Roll a saving throw against intelligence"""
try:
return roll(self.intel ligence) threshold
except AttributeError:
# character has no intelligence, so always fails
return False

Yes, you can make that easier with currying, decorators etc. but why not
make sure your characters have the required attributes in the first place?

One way of doing that would be to add default values for the required
attributes in the class, and let instances inherit those defaults from the
class.

and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.
If you've got that many character attributes, I'm guessing that your game
will be a tad hard to play :-)

If you have more than a half-dozen or ten character attributes, you could
consider encapsulating them in some way. E.g. group-related attributes and
pass them as tuples:

power =(constitution, health, anaerobic_stren gth, aerobic_strengt h)
intelligence =(IQ, wisdom, dexterity, book_learning, street_wisdom)
charisma =(beauty, chutzpah, attractiveness, persuasiveness)
senses =(vision, hearing, smell, telepathy, empathy, feeling, spacial)
others =(luck, determination, laziness, attention_to_de tail)

You could then roll against power, say, by giving a set of weights:

character.roll( 'power', (0.0, 0.0, 0.9, 0.1))

gives anaerobic strength a weighting of 90% and aerobic 10%.

But again, I think that if your roll-playing game needs to have such
fine-grained attributes, I think it will be too complex to be fun.
Or maybe there's some way to loop through two lists (the stats and the
attributes) and assign them that way? I was thinking of a nested for
statement but that didn't seem to work.
def __init__(self, stats):
names = ['strength', 'dexterity', 'intelligence', 'luck']
for name, stat in zip(names, stats):
setattr(self, name, stat)

--
Steven.

Nov 7 '06 #5
John Salerno <jo******@NOSPA Mgmail.comwrite s:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats
instead?
A tuple is fine, but assumes that there is a logical *sequence* to
these values. If that's true, it should be no problem to assign them as:

class Character(objec t):
def __init__(self, name, stats):
self.name = name
(self.strength, self.dexterity,
self.intelligen ce, self.luck) = stats
>>foo = Character("Foo" , (10, 11, 9, 10))
print foo.name, foo.strength, foo.intelligenc e
Foo 10 9

In this case, though, I don't see any value in a specific sequence, so
a mapping looks better to me and gives the caller more flexibility in
how to set it up.

class Character(objec t):
stat_keys = ['strength', 'dexterity', 'intelligence', 'luck']
def __init__(self, name, stats):
self.name = name
self.stats = {}
for (stat_key, stat_value) in [(k, stats[k])
for k in self.stat_keys]:
setattr(self, stat_key, stat_value)
>>foo = Character("Foo" , dict(
... dexterity = 11, luck = 10,
... strength = 10, intelligence = 9,
... ))
>>print foo.name, foo.strength, foo.intelligenc e
Foo 10 9
I'm trying to think ahead to when I might want to add new
attributes
In which case you almost certainly want a mapping, not a sequence.
and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.
This is one of the many reasons why Python's built-in composite types
are so useful. A group of semantically-related values can be passed as
a single composite value.

--
\ "I hope that after I die, people will say of me: 'That guy sure |
`\ owed me a lot of money.'" -- Jack Handey |
_o__) |
Ben Finney

Nov 7 '06 #6
Larry Bates <la*********@we bsafe.comwrote:
John Salerno wrote:
Let's say I'm making a game and I have this base class:

class Character(objec t):

def __init__(self, name, stats):
self.name = name
self.strength = stats[0]
self.dexterity = stats[1]
self.intelligen ce = stats[2]
self.luck = stats[3]

Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?

I'm trying to think ahead to when I might want to add new attributes,
and I want to make sure this doesn't get crazy with individual
parameters instead of just the one list.

Or maybe there's some way to loop through two lists (the stats and the
attributes) and assign them that way? I was thinking of a nested for
statement but that didn't seem to work.

Sounds like what you should be doing is something like keyword arguments
instead.

class Character(objec t):
def __init__(self, name, **kwargs):
self.name=name
for key, value in kwargs.items():
setattr(self, key, value)
z=Character('na me', strength=10, dexterity=5, intelligence=3,
luck=0)
I would say this is a bad idea because you'll get no error messages if
you mis-spell 'dexterity' for instance.

I'd prefer to see a bit more error checking, something like

class Character(objec t):
attributes = set(['strength', 'dexterity', 'intelligence', 'luck'])
def __init__(self, name, **kwargs):
self.name=name
for key, value in kwargs.items():
if key not in self.attributes :
raise AttributeError( "Bad attribute %s for %s" % (key, self.__class__. __name__))
setattr(self, key, value)
z = Character('name ', strength=10, dexterity=5, intelligence=3, luck=0)
>>Character('na me', strength=10, dexterity=5, intelligence=3, luck=0)
<Character object at 0xb7dac72c>
>>Character('na me', strength=10, dextrity=5, intelligence=3, luck=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "z.py", line 7, in __init__
raise AttributeError( "Bad attribute %s for %s" % (key, self.__class__. __name__))
AttributeError: Bad attribute dextrity for Character
>>>
You can then add to attributes in the subclasses

class MagicCharacter( Character):
attributes = Character.attri butes | set(['spells', 'wand'])
>>MagicCharacte r('name', strength=10, dexterity=5, intelligence=3, luck=0, spells=1)
<MagicCharact er object at 0xb7ce86ac>
>>>
If I was writing this, I'd probably just stick to named parameters
unless I had more than 10 parameters. Named parameters are easy to
manage, and you never get confused by their position.

Also pychecker understands named parameters where as if you use a
scheme like the above you'll cause pychecker problems!

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Nov 7 '06 #7
John Salerno wrote:
Is this a good way to assign the values to the different attributes?
Should 'stats' be a list/tuple (like this), or should I do *stats instead?
Thanks guys! The main suggestion seems to be to use setattr(), so I
might give that a try. But I do like Steve's suggestion that it's better
to be explicit about each attribute, instead of just accepting a list of
numbers (but I can't help but feel that for some reason this is better,
because it's more general). We shall see! :)
Nov 7 '06 #8
John Salerno <jo******@NOSPA Mgmail.comwrite s:
But I do like Steve's suggestion that it's better to be explicit
about each attribute, instead of just accepting a list of numbers
(but I can't help but feel that for some reason this is better,
because it's more general).
If you pass a *mapping* of the "I-might-want-to-add-more-in-the-future"
values, then you get both explicit *and* expandable, without an
arbitrary unneeded sequence.

--
\ "He may look like an idiot and talk like an idiot but don't let |
`\ that fool you. He really is an idiot." -- Groucho Marx |
_o__) |
Ben Finney

Nov 7 '06 #9
Ben Finney wrote:
John Salerno <jo******@NOSPA Mgmail.comwrite s:
>But I do like Steve's suggestion that it's better to be explicit
about each attribute, instead of just accepting a list of numbers
(but I can't help but feel that for some reason this is better,
because it's more general).

If you pass a *mapping* of the "I-might-want-to-add-more-in-the-future"
values, then you get both explicit *and* expandable, without an
arbitrary unneeded sequence.
Do you mean by using the **kwargs parameter? If I do this, doesn't it
mean that *anything* could be added though? Misspelled words and
completely unrelated attributes as well?

Or does this matter as long as you are handling the processing yourself
internally and not allowing users access to the Character class?
Nov 8 '06 #10

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

Similar topics

1
5980
by: Josh | last post by:
Caution, newbie approaching... I'm trying to come up with a very simple Tkinter test application that consists of a window with a drop-down menu bar at the top and a grid of colored rectangles filling the remainder of the window. Mind you, this is a contrived test application to help me understand Tkinter and Python, not an actual application yet. I've trivially subclassed Tkinter.Canvas into ColorCanvas, added a bunch of ColorCanvases...
10
1817
by: Matthew Sims | last post by:
Python Newbie here. This is my first time learning object-oriented programming and trying to break out of the usual Korn/Perl/PHP style of programming. Having some difficulty understand some items. For lists, I understand this: C= print C some But I can't seem to do this:
13
1943
by: Frans Englich | last post by:
Hello, I am having trouble with throwing class instances around. Perhaps I'm approaching my goals with the wrong solution, but here's nevertheless a stripped down example which demonstrates my scenario: #------------------------------------------------------------------------------------------ class foo: tests = {}
14
74868
by: Eric Bantock | last post by:
Very basic question I'm afraid. Once an array has been declared, is there a less tedious way of assigning values to its members than the following: myarray=8; myarray=3; myarray=4; myarray=0; myarray=0; myarray=1; myarray=8;
23
1709
by: Antoon Pardon | last post by:
I know this PEP is rejected. However I have a problem that would benefit from having extreme values and the sample implementation that is given in the PEP is unsatifactory for my purpose. I had written my own module, which works similarly but is somewhat extended. Here is an example of how it can be used and how I would like to use it but get stuck. from extreme import Top
10
1547
by: Alan G Isaac | last post by:
My class MyClass reuses many default parameters with a small number of changes in each instance. For various reasons I decided to put all the parameters in a separate Params class, instances of which reset the default values based on keyword arguments, like this: class Params: def __init__(self,**kwargs): #set lots of default values
5
1656
by: Manuel Graune | last post by:
Hello, while trying to learn how to program using objects in python (up to now simple scripts were sufficient for my needs) I stumbled over the a problem while assigning values to an object. The following piece of code shows what I intend to do: <---snip--->
7
1443
by: George Sakkis | last post by:
A situation that often comes up is having to initialize several instance attributes that accept a default value. For a single class, passing the default values in __init__ is fine: class Base(object): def __init__(self, x=0, y=None): self.x = x self.y = y For inherited classes that need to override __init__ while keeping a
1
1525
by: The Pythonista | last post by:
I've been wondering for a while about whether assigning to __class__ is bad form or not. Specifically, I mean doing so when some other method of implementing the functionality you're after is available (i.e. using an adapter, or something like the strategy pattern). To give an example and a non-example of what I'm talking about, consider the following recipes from the online Python Cookbook: Ring Buffer:...
0
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9027
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8895
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4369
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.