How to use a class variable in a function? - python

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.

Related

Can you reference a class name with a variable?

I am making an RPG text based game with classes and subclasses. I'm importing other python files, each of which have their own classes. Each python file is the name of their RPG main class, each of which have multiple classes for the respective RPG subclass. My question is, if I wanted to access a variable from one of these classes from the main file (E.G. if I wanted to access the bard's spellist I'd do Bard.Bard.Spellist, (First bard being the file import, second being the name of the class), could I use a variable like:
x = input("Enter class from which to access the spellist: )
print(x.x.spellist)
hope that makes sense!
This is what I tried:
x = Bard
for item in x.x.SpellBook:
print(item, ":", x.x.SpellBook[item])
I expected it to print a list of the names and spell level like this:
(spellname) : (spellevel)
It comes up with this error:
Traceback (most recent call last):
File "main.py", line 82, in <module>
for item in x.x.SpellBook:
AttributeError: module 'ClassFold.Bard' has no attribute 'x'
While you can do what you're asking (through a combination of globals() and getattr), it's a bad idea to do so. Your variable names should not be data in your program. Variable names are for you the programmer to use, not for your users.
Instead, use a dictionary or some other data structure to map from one kind of data (e.g. a string like 'bard') to another kind of data (e.g. the bard.Bard class). Use that mapping to process the user input into the data you actually need to use.
Here's a very simplified example:
class Bard:
spell_list = ['x', 'y', 'z']
class_name_mapping = {'bard': Bard, 'fighter': ...}
user_class_name = input('What class is your character? ')
user_class = class_name_mapping[user_class_name.lower()]
user_spell_list = user_class.spell_list
print(f'Your spells are: {", ".join(user_spell_list)}.')

What is the 'attribute error in my code' ? Analyse it

I am coding for to workout this question
Question
Using the concept of object oriented programming and inheritance, create a super class named Computer, which has two sub classes named Desktop and Laptop.
Define two methods in the Computer class named getspecs and displayspecs, to get the specifications and display the specifications of the computer.
You can use any specifications which you want.
The Desktop class and the Laptop class should have one specification which is exclusive to them for example laptop can have weight as a special specification.
Make sure that the sub classes have their own methods to get and display their special specification.
Create an object of laptop/ desktop and make sure to call all the methods from the computer class as well as the methods from the own class.
My solution for this is
class Computer:
def __init__(self, ram, gfx, backlit):
self.ram = ram
self.gfx = gfx
self.backlit = backlit
def getspecs(self):
self.ram = (input('RAM: '))
self.gfx = (input('GFX: '))
self.backlit = (input('Backlit: '))
def displayspecs(self):
print('RAM: ', self.ram, 'GFX: ', self.gfx, 'Backlit: ', self.backlit)
class Laptop(Computer):
def __init__(self, weight):
self.weight = weight
def getspecs_laptop(self):
self.weight = (input('Enter Weight: '))
def displayspecs_laptop(self):
print('Weight: ', self.weight)
class Desktop(Computer):
def __init__(self, size):
self.size = size
def getspecs_desktop(self):
self.size = (input('Enter Size: '))
def displayspecs_desktop(self):
print('Size:', self.size)
Computer1 = Laptop
Computer1.getspecs(1)
Computer1.getspecs_laptop(2)
Computer1.displayspecs(3)
Computer1.displayspecs_laptop(5)
Computer1.displayspecs(4)
Computer2 = Desktop
Computer2.getspecs(6)
Computer2.getspecs_desktop(7)
Computer2.displayspecs(9)
Computer2.displayspecs_desktop(99)
OUTPUT -
"D:\Coding\Python Exercises\Ass6\venv\Scripts\python.exe" "D:/Coding/Python Exercises/Ass6/Demo1.py"
RAM: 1
Traceback (most recent call last):
File "D:/Coding/Python Exercises/Ass6/Demo1.py", line 43, in <module>
Computer1.getspecs(1)
File "D:/Coding/Python Exercises/Ass6/Demo1.py", line 9, in getspecs
self.ram = (input('RAM: '))
AttributeError: 'int' object has no attribute 'ram'
Process finished with exit code 1
What is the mistake I am doing?
What needs to be given in the parent-thesis in the defined
objects?
Computer1.getspecs(here What needs to be added?)
When I run it without giving any value in it, I get error
TypeError: getspecs() missing 1 required positional argument: 'self'
There are far too many errors in this code to give you a simple answer. However, I can help with the first few:
Most of all, you wrote a lot of code without testing any of it. As a result, you now have to fix several errors at once to get any useful output. Comment out your main program for now. Instead, test your Computer class before you try to work with a Laptop or Desktop.
You need to instantiate an object of the class. Then you can use the class methods the way you want. In particular, Computer1 = Laptop(3.5) will give you a Laptop object of some weight.
Note that each of your __init__ methods has at least one required argument. Comment those out until you get used to working with basic objects.
I hope this will allow you to make some progress with your code.

How to use a dictionary that's been declared and filled in another file in Python?

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.

issue with list error in python class

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

Object has no attribute - python class execution

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.

Categories