-1

In this (test) code:

class Test(object):
  def __init__(self,val):
    self.val=val
  def returnVal(self):
    return(self.val)

dict = {}
dict["Tom"] = Test(20)

How do I get Tom to use the 'returnVal' function. As Tom.returnVal() doesn't seem to work. (Sorry if this is a silly question, this is my first time using dictionaries for objects.

Xaeol
  • 101
  • 6
  • You can also do `dict.get("Tom").returnVal()`. Also your question is nice but may I tell you that some people might not like it & downvote it so probably in the future :) – Ice Bear Dec 19 '20 at 05:04

3 Answers3

2

Maybe you should change the codes a little bit

class Test(object):

  def __init__(self,val):
    self.val=val
  def returnVal(self):
    return self.val   # return not only print

dict = {}
dict["Tom"] = Test(20)

And Tom is not an object, it is a key of the dict. So you should code like this:

dict["Tom"].returnVal()
Jerry An
  • 1,077
  • 10
  • 18
1

You use the key value to select the element from the dictionary, just like you did when you assigned it.

dict["Tom"].returnVal()

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
0

There are actually a few more things you can learn that are relevant in your post.

First, since Python 3.x you do not need to sub-class your classes from object. It is automatic. See this thread here (including some relevant comments).

So you can probably do:

class Test:
  def __init__(self,value):
    self.value = value

  def value(self):
    return self.value

You might consider if you really want the method value. In Python, if the only thing you need is to read an attribute value (no additional processing, no access control, no nothing), there is no need for a getter method. Accessing the attribute directly from the instance will do:

obj = Test(42)
value = obj.value 

Additionally the naming style for methods and functions in Python should be snake_case, with CamelCase for class names. For other styles see PEP8

Even more important, do not assign to built-in names, such as dict or list:

# do not do this
dict = {}
dict["Tom"] = Test(20)

To see other names you should avoid using, do in the Python shell:

>>> import builtins
>>> dir(builtins)

This is because you replace the built-in definition, and you will get confused in later code. In your code above dict is from now on a specific dictionary instance object, and creating a new dictionary with dict() will fail.

Maybe you just wanted to create an object with

tom = Test(20)
print(tom.value)

Or to store Test objects (or objects of any type) in a dict:

people = {}
people["Tom"] = Test(20)
print(people["Tom"].value)
print("Tom" in people)
progmatico
  • 4,714
  • 1
  • 16
  • 27