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)