This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 1 year ago.
I am trying to make a program to simulate movement. This is the code
class Object:
forc={}
srtpos = 0
vel = 0
def __init__(self,mass, srtpos = 0):
self.mass = mass
self.srtpos = 0
def UpVel(vel, time = 1, a = 0):
vel1 = vel + a*t
vel = vel1
def Move(self, vel, time = 1, a = 0):
self.srtpos+= self.vel*time +(0.5)*a*(time**2)
UpVel(self.vel, time, a)
a = Object(5)
print(a.srtpos)
for i in range(5):
a.Move(5)
print(a.srtpos)
The UpVel() function is updating the velocity. When i try to run this through the Move() function, the program is giving me error
Traceback (most recent call last):
File "/media/atharva/DATA/Python/PhySim.py", line 17, in <module>
a.Move(5)
File "/media/atharva/DATA/Python/PhySim.py", line 13, in Move
UpVel(self.vel, time, a)
NameError: name 'UpVel' is not defined
I have tried putting the function call in __main__ and also changing the name of the function.
Any help appreciated.
Thanks in advance.
Try to use
self.UpVel(self.vel, time, a)
If you want to use it without self. it needs to be a static method.
Related
This question already has answers here:
How can I call a function within a class?
(2 answers)
function name is undefined in python class [duplicate]
(2 answers)
Closed 1 year ago.
main code
import matplotlib.pyplot as plt
from refract import random_move
while True:
rw = random_move(5000)
rw.track()
pointsv = list(range(rw.points))
fed = input("you need scatter/ plot: y/n ")
if fed == 'y':
plt.scatter(rw.xv,rw.yv, c= pointsv ,cmap=plt.cm.Greens, s = 2)
plt.show()
if fed == 'n':
plt.plot(rw.xv,rw.yv, c = [0,0.5,0.5], linewidth = 2)
plt.show()
class definition
class .....................
from random import choice
class random_move():
def __init__(self,points):
self.xv = [0]
self.yv = [0]
self.points= points
def track(self):
xv= getstep()
yv= getstep()
def getstep(self):
dxv = [0]
while len(dxv) < self.points:
xd = choice([1])
xva = choice([3,4,5,7,8,9])
xt= xd*xva
if xt == 0:
continue
nx = dxv[-1]+xt
dxv.append(nx)
return dxv
final output:
error:
---------------------------------------------------------------------------
NameError: name 'getstep' is not defined
try it;
def track(self):
self.xv= self.getstep()
self.yv= self.getstep()
You have to call the method of the class via the object from the class or via the class itself passing an object of that class. In your case, to call track method, you should call self.getstep() or random_move.getstep(an_obj_of_the_class)
This question already has an answer here:
Python- how to get list of self variables in a class consist of N-self
(1 answer)
Closed 6 years ago.
I am using mesa for my program. I am trying to execute my Model Class, but I got AttributeError from the Agent Class.
This is my script:
class ComtrModel (Model):
""" A model with some number of Agents"""
def __init__(self,N):
self.num_agents = N
self.schedule = RandomActivation(self)
for i in range (N):
a = CommuterAgent(i)
self.schedule.add(a)
class CommuterAgent (Agent):
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
def step(self):
if self.distance >= 10000:
self.update_need = self.update_need()
return
def update_need (self, famsize):
if self.famsize :
self.famsize = famsize
return
prob_need()
How to get variables of each agent? I need to check it to make sure the model run properly.
So far this is my code to execute (on interactive session):
from src.ComtrModel import *
model = ComtrModel(5)
for i in range (10):
model.step()
for key, value in CommuterAgent.step(model):
print(key, value)
EDIT : But it returns
Traceback (most recent call last):
File "C:src/__init__.py", line 3, in <module>
from src.ComtrModel import *
File "C:\src\__init__.py", line 9, in <module>
for key, value in CommuterAgent.step(model):
File "C:\src\ComtrModel.py", line 40, in step
if self.distance >= 10000:
AttributeError: 'ComtrModel' object has no attribute 'distance'
I also have tried something like this:
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
But it only works for single object
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
Doesn't look correct. You don't pass famsize and distance as parameters.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a class inside a file called Weapons.py called Pistol that looks like this:
class Pistol(object):
MAXAMMO = 6
def __init__(self, ammo):
if(ammo <= self.MAXAMMO):
self.ammo = ammo
def shoot(self):
if(ammo > 0):
accuracy = random.randint(0, 3)
return 3 * accuracy
ammo -= 1
else:
print("No ammo")
And a class called ColtM1911 that inherits from Pistol. It looks like this:
class ColtM1911(Pistol):
MAXAMMO = 7
def __init__(self, ammo):
self.ammo = 7
When I run:
import Player
import SetUp
from Utils import *
import pickle
import TitleAnimation
import os
import SaveLoad
from Weapons import *
gun = ColtM1911(5)
In another file it gives me "TypeError: object() takes no parameters" When trying this in the shell it worked, so I suspect it is to do with having it in a separate file.
The full traceback is,
Traceback (most recent call last):
File "C:\Users\James\Documents\game.py", line 3, in <module>
gun = Weapons.ColtM1911(5)
TypeError: object() takes no parameters
The only way I can recreate your error is if Pistol is actually defined as:
class Pistol(object()):
# ^ note extraneous parentheses
In Python 3.x, you don't need object at all; all classes are new-style by default. Also, there are logic errors and M1911.__init__ is redundant. Try something like:
import random
class Pistol:
MAXAMMO = 6
def __init__(self, ammo):
if ammo <= self.MAXAMMO:
self.ammo = ammo
else:
# what do you want do do here? Raise an error? Set ammo = MAXAMMO?
def shoot(self):
if self.ammo > 0:
self.ammo -= 1
return 3 * random.randint(0, 3)
else:
print("No ammo")
class ColtM1911(Pistol):
MAXAMMO = 7
I've been following along with this series of youtube videos in order to get a more hands on approach to python. I don't have a deep understanding of what some of the code does, but I more or less get what each piece is supposed to achieve, even though I may not be sure how.
I'm getting a Syntax error on the last line here:
class Character(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
self.dead = False
def attack(self, other):
pass
def update(self):
if self.hp < 0 #Error's on this line
self.dead = True
self.hp = 0
Here is the traceback:
Traceback (most recent call last): File "game.py", line 4, in
<module>
from Characters.player import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/player.py", line 2,
in <module>
from character import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/character.py", line
12
if self.hp < 0
^ SyntaxError: invalid syntax
You forgot a colon (:) at the end of the line:
if hp < 0:
Your init also looks like a constructor. As such, it should likely be __init__ instead of init. Otherwise, you're going to run into problems with it not being executed at object instantiation.
i'm having a problem in my unit tests, i don't know why, I'm gotting the following stack:
Traceback (most recent call last):
File "novaapiclient_tests.py", line 11, in test_create_server
nova = novaapiclient.NovaAPIClient()
TypeError: __init__() takes exactly 2 arguments (1 given)
follow my test code:
class TestFunction(unittest.TestCase):
def setUp(self):
self.nova = novaapiclient.NovaAPIClient()
def test_create_server(self):
self.setUp()
lsbf = self.nova.lst_of_servers(self.nova.listServers())
image = "3f9e6696-2ed2-4e06-ae16-c828062addbe"
flavor = "m1.tiny"
name = "testing_unit"
self.nova.createServer(image, flavor, name)
time.sleep(60)
lsaf = self.nova.lst_of_servers(self.nova.listServers())
if(len(lsbf) < len(lsaf)):
assertTrue(True)
else:
assertTrue(False)
def delete_server(self):
self.setUp()
serv_id = "13e0c3de-d736-47ec-bc22-3a794aa3e2a9"
self.nova.deleteServer(serv_id)
ls = self.nova.lst_of_servers(self.nova.listServers())
j = 0
fin = False
while(j < 3 and not fin):
time.sleep(75)
for i in range(len(ls)):
if(serv_id == str(ls[i])):
assertTrue(False)
break
assertTrue(True)
fin = True
break
j += 1
I tried to create a init method and cut the "self" in the methods, but i continues printing the error.
The novaapiclient.NovaAPIClient constructor needs to receive an argument, but you aren't passing any.
In this question of yours you did pass an argument to novaapiclient.NovaAPIClient, so I assume you need to do something similar.