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?
micksulley
 
Posts: 7
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 irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 774
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):
      self.name = name
      #other

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
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1377
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: metulburr and 1 guest