How to access self.key

This is the place for queries that don't fit in any of the other categories.

How to access self.key

Postby micksulley » Wed Apr 24, 2013 11:45 pm

I have a class and then a dictionary of instances of the class. Within a method in the class I would like to check the key of the current object, something like

Code: Select all
class xyz:
def methd(self):
  if self.key = 'ABC':
    print('This is ABC')

d = {}

d['ABC'] = xyz()

but self.key does not work. How do I do it?
User avatar
Posts: 31
Joined: Tue Mar 26, 2013 9:08 pm

Re: How to access self.key

Postby Yoriz » Wed Apr 24, 2013 11:55 pm

Class names should be CamelCase.
Your indentations is wrong def is at the same level as class.
Indents should be 4 spaces.
You have not initialized self.key with a value.
A single '=' is for assigning a value to check for a value use double '=='.
The dictionary key 'ABC' is just the key that the instance of class Xyz is stored against in d, the instance of Xyz knows nothing about dictionary d.
New Users, Read This
Join the #python-forum IRC channel on!
User avatar
Posts: 1588
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: How to access self.key

Postby metulburr » Thu Apr 25, 2013 1:52 am

her is a raw example, and when i saw raw i mean raw. I am not sure exactly what you are doing, but here is something like what i think you are doing, not sure though.

Code: Select all
class Employee:
   def __init__(self, name): = name

names = ['john', 'jacob', 'jingleheimer', 'schmidt']
instances = {}

for name in names:
   instances.update( {name:Employee(name)} )
print('instances are: {}'.format(instances))
print('instances[\'john\'] is: {}'.format(instances['john']))

where instances['john'] is the dictionary key to the value, being the instance object, which currently only contains the same name as the key anyways.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
User avatar
Posts: 2120
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Return to General Coding Help

Who is online

Users browsing this forum: Cartman and 6 guests