Class intSet
I'm trying to understand the following code from the MIT python class. When i create an object of the class intSet as follows i run into some trouble with one of the attributes.
s=intSet()
and try
s.vals()
I get the following error
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
s.vals()
TypeError: 'list' object is not callable
why is this? I've been told i shouldn't try s.vals directly because of data hiding, when i try s.vals the correct list is returned but i get an error when trying s.vals(). Can someone explain this error? I'm new to both OOP and python so i apologise for my poor questioning. Any help is greatly appreciated.
vals is not a method it is an attribute so you can't call it. In python the parentheses indicate you are calling a method. So just do s.vals
When you use s.vals() it tries to call function 'vals' through variable 's' whereas, when you use s.vals it doesnt look for the function just returns the value stored in s.vals.
You are trying to call vals that is a list. You are doing something like this [](), that is not possible.
What you should do in OOP way is to declare getter function like that:
class intSet(object):
def __init__(self):
self.__vals = [] # kinda private class instance
# .... other code
#property
def vals(self):
return self.__vals
intset = intSet()
intset.vals # is that list
More info about private members in python and about properties
Related
I created a class and specified the attributes of the member with the following code:
Mexico_66 = Product('Mexico 66 VIN', 99.90, 4)
In the class, I have defined the following magic method:
def __len__(self):
print(self.quantity)
When I try to use this magic method with the following syntax: len(Mexico_66), the code executes but gives off an error at the very end: TypeError: 'NoneType' object cannot be interpreted as an integer
However, when executing the code with the following syntax: Mexico_66.len(), no error appears.
I don't quite understand why the error is caused in the first case and what is the difference between the 1st and 2nd options of executing magic method. I would be grateful if someone could explain it.
The __len__ magic method is supposed to return something, in this case, probably return self.quantity. You are getting the type error because your method implicitly returns None.
The idea of using these magic methods is to define behavior for commonly used functions like len(). If you call it using instance.__len__(), you are not utilizing the magic method, you are simply calling it like a regular instance method, which is why you don't see any error in that use case
First of all I apologize if I have writen some word incorrectly - English is my second language.
But anyway I've been working on an text RPG for like a week and just started on an combat system and I have all of the player and enemy statistics in clases.
This is just part of my code but it's enough. So I have made a function which levels up my character.
class player:
def __init__(self):
self.name='Hero'
self.lvl=1
self.xp=0
self.lvl_next=25
self.str=1
self.dex=1
self.int=1
def pl_level(self):
Nstr=0
Ndex=0
Nint=0
while player.xp>=player.lvl_next:
player.lvl+=1
player.xp-=player.lvl_next
player.lvl_next=round(player.lvl_next*1.5)
Nstr+=1
Ndex+=1
Nint+=1
print('Level:', player.lvl)
print('STR {} +{} DEX {} +{} INT {} +{}'.format(player.str, Nstr, player.dex, Ndex, player.int, Nint))
player.str+=Nstr
player.dex+=Ndex
player.int+=Nint
print('Exp: '+str(player.xp))
print('To the next level: {}%'.format(int((player.xp/player.lvl_next)*100)))
print('Next:', player.lvl_next)
But I don't know why it just does not work.
I've tried to simplify my code because well maybe thats how i'll find the problem. But it just keeps shoving me this error.
Traceback (most recent call last):
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 99, in <module>
pl_level()
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 11, in pl_level
while player.xp>=player.lvl_next:
AttributeError: type object 'player' has no attribute 'xp'
Even tho you can see that in init there is self.xp.
So how can I fix this?
Use that like self.px inside other methods or else if you want to use like that only make it player().px instead of player.px.As your class needs to be to initialized first before using any of its variables or methods.
Better to access class variables in same class by using self as good practice.
I am having trouble trying to import a dictionary object that I have declared and filled with key,value pairs in another Python file.
A bit of background -- I am working with accessing the Reddit API and then filling a dictionary with subreddit names and a score I have given them, based off of Reddit comments that have been retrieved. My main goal with importing the dictionary is in order to find a way to work with said dictionary of data, to mess around with, without having to make repeated calls to the API and having to wait to keep refilling the dictionary each time I want to test if it runs.
At the moment, I have looked around the internet and other questions on StackOverflow about importing just a dictionary object from another file and class and I keep getting the same error where it says that the 'module' object has no attribute. Please see my example below:
from subreddit_score import main
# the dictionary obj that I wish to use in subreddit_score.py is called top_five
d = subreddit_score.top_five
I'm unsure as to why this is, so if someone would be able to help me I would greatly appreciate it.
Also: if there is a better way to do this, I would also appreciate any input. But I am mainly just asking for a way to import a dictionary variable.
Thanks!
EDIT:
Traceback error:
Traceback (most recent call last):
File "tester.py", line 8, in <module>
d = subreddit_score.top_five
AttributeError: 'module' object has no attribute 'top_five'
subreddit_score.py
def main():
# fetchRedditData() returns a dictionary
top_five = fetchRedditData()
from subreddit_score import main
# the dictionary obj that I wish to use in subreddit_score.py is called top_five
d = subreddit_score.top_five
You're getting the "'module' object has no attribute" error because you are trying to get the value of top_five but it's in a function, not a member of the module which could be accessed from anywhere.
To fix this, you could either change the main() function you have into a getter type object (also, you probably should name this function something other than main)
def main():
# fetchRedditData() returns a dictionary
top_five = fetchRedditData
return top_five
Or if you want to access the dictionary as a member object, you could just make it global within the file, but I would recommend against this as it is poor design,
top_five is local to the function main in your subreddit_score module. Because it's not in the module scope, you cannot access it as though it was - in a similar way, you won't be able to access it from other functions in the same module.
The quickest fix to this, would be to just make it a global in the module, although this is likely not the best design:
top_five = None
def main():
global top_five
top_five = fetchRedditData()
Now you can access top_five from another module that imports this module, but you're temporally coupled to having run main first.
Im trying to run some tests in python. Im using Unittest framework.
The test "test_processJson" uses a test Json, dictTestString, and then checks if it has one or more elements. This is my script "testing.py"
import json
import starter#The code Im trying to test
import unittest
class MyTests(unittest.TestCase):
def test_processJson(json):
dictTestString = '{"city":"Barcelona"}'
jTest = json.loads(dictTestString)
dictProcess = starter.processJson(dictTest)
self.assertEquals(dictProcess["city"], "Barcelona")
if __name__ == '__main__':
unittest.main()
The problem comes when I run the test I get this error:
Traceback (most recent call last):
File "testing.py", line 16, in test_processJson
jTest = json.loads(dictTestString)
AttributeError: 'MyTests' object has no attribute 'loads'
I'm new to python, so I've been looking for an answer but any of the mistakes I've seen Im not doing.
Any help will be appreciated.
Thanks.
Your function's argument is named json, which shadow's the global json module. Actually since this is the first argument of a method, it get bound to the current MyTest instance, and since unittest test methods only expect the current instance as argument AND you don't have any need for a json argument here, you just have to rename it to self (which is the convention for the first argument of instance methods) and you problem will be solved.
NB : There are a couple other typos / issues with your code but I leave it up to you to find and solve them - that's part of the fun isn't it ?
I've searched for an answer to this problem, but I can't find an answer, it may be too specific.
I have a simple program, my first proper program and I've created it mainly as practice:
import math
class Logs(object):
def __init__(self,a,b):
self.a = a
self.b = b
def apply_log(self):
self.a_log = math.log10(self.a)
self.b_log = math.log10(self.b)
return (self.a_log, self.b_log)
def add_log(self):
self.log_add = self.a_log + self.b_log
return self.log_add
def log_split(self):
self.log_c = self.log_add // 1
self.log_m = self.log_add % 1
return(self.log_c, self.log_m)
def result(self):
self.ex_m = 10 ** self.log_m
self.ex_v = 10 ** self.log_c
self.log_res = self.ex_m * self.ex_v
return self.log_res
lg = Logs(34,54)
#print(lg.apply_log())
#print(lg.add_log())
#print(lg.log_split())
print(lg.result())
The program runs perfectly when I uncomment out all the print statements and run them at the same time. However, if I just want to print the result for the instance and comment out the three other print statements, it throws an error:
Traceback (most recent call last):
File "python", line 33, in <module>
File "python", line 24, in result
AttributeError: 'Logs' object has no attribute 'log_m'
I don't understand why it would work when printing out the results of each method or why this would affect how the program would run.
I'll also say right now that this is the first time I've used a class (the point of the program was practice for creating a class) so I imagine the error is in the way I've created it.
Any help would be very much appreciated!
Thanks
It has to throw the AttributeError because log_m is initialized in the method log_split and used in the method result. If you call result without calling log_split before, log_m is not defined and you get the error that you are seeing. This class is designed in a way that result can only be called after log_split.
log_m is a local variable inside your log_split(self) function.
So inside the result(self) function, the log_m and log_c are two variables unknown to the function.
So you have to run log_split() first and then result().
The value of log_m is initialized in log_split method, and it is dependent on the value of log_add which is initialized in add_log method. Moreover, log_add is dependent on the value of a_log and b_log which are initialized in apply_log method. Hence, it shows the AttributeError when you comment all the three implementations of the methods.
You have to maintain the sequence of method calling, otherwise commenting any of the methods will cause the error.