Creating and Using a class - python

class UniversityAthletics():
def _init_(self, university_name, sport):
self.university_name = university_name
self.sport = sport
def describe_athletics(self):
print(self.university_name.title() + " " + self.sport.title())
def in_season(self):
print(self.sport.title() + " is in season.")
athletics = UniversityAthletics('salisbury university', 'soccer')
print("The school name is " + athletics.university_name.title() + ".")
print(str(athletics.sport.title()) + " is in season")
athletics.describe_athletics()
athletics.in_season()
Guys, I'm just learning how to code so if I say something that makes no sense my apologies.
But I'm trying to give the class UniversityAthletics the attributes
'salisbury university', 'soccer'
but when I try to execute the program I get this error
Traceback (most recent call last): File "E:/WorWic/IntroToProgramming/chapter9/University Athletics.py", line 13, in
athletics = UniversityAthletics('salisbury university', 'soccer') TypeError: object() takes no parameters
I've gone back to the book that my professor gave me and still cannot find a solution. There must be something simple and plain that I missed.

Your init method is named _init_ (one underscore on each side), when it should be __init__ (two underscores on each side).
Because the method is named wrong, python is not finding it, and instead directly calling the method in the superclass of your class, which is:
object.__init__
and passing it your two parameters, which it is not expecting.. hence the error message.

The __init__ function needs double underscores on either sides (you have only singles).

It's 2 lines around the init, so instead of _init_ type __init__.

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)}.')

I'm getting Name error for my python class attributes

I've just started learning Python and I was trying out class concept and came across this error and cant find out what I've done wrong ! Can someone point out ?!
class animal:
def __init__(self,name,ani,age,location):
self.name= name
self.ani = ani
self.age = age
self.location = location
def info(self):
print("I'm a {0} called {1} and I'm {2} years old, living in {3}".format(ani,name,age,location))
Arun = animal(Martin,Dog,7,Amazon)
Arun.info()
And the error is :
Traceback (most recent call last): File
"C:\Users\DELL\Desktop\python\class_trail.py", line 12, in <module>
Arun = animal(Martin,Dog,7,Amazon) NameError: name 'Martin' is not defined
So a couple of things have gone wrong with your code:
You are passing in variable names, not strings.
When you call Arun = animal(Martin,Dog,7,Amazon), Python looks for a variable name called Martin, but doesn't find one and raises NameError.
What you probably intended was Arun = animal('Martin','Dog',7,'Amazon')
Your .info() method needs to refer to self.ani and self.age etc., because those data items are bound up inside the object.
Arun = animal(Martin,Dog,7,Amazon)
^ you want to pass here string values, but instead you're passing there variables which are not defined. To pass there strings you have to wrap them into quotes like this:
Arun = animal("Martin","Dog",7,"Amazon")
The error you are getting refers to the fact that no variable Martin is defined in the code, before you use it. What you probably meant to do is
Arun = animal("Martin", "Dog", 7, "Amazon")
Note the quotes around the strings you are passing as parameters, as opposed to how python interprets your code, where this would work:
name = "Martin"
animal = "Dog"
age = 7
location = "Amazon"
Arun = animal(name, animal, age, location)
Extra: something you may want to get used to while learning to code in Python are its good practices. Python classes are typically declared with a capital letter (or actually PascalCase), like so class Animal():, while variable names are typically declared lower case (snake_case), like so arun = Animal(...).
There is a small exception: constants are declared all capital, like so EULER_CONSTANT = 0.577.

How to use a class variable in a function?

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.

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.

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