Python - mesa : How to get instance variables of each object [duplicate] - python

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.

Related

Python NameError:

I am new to learning Python and currently I am working on Classes. Below is a program that I am referring to. However, on calling the class, I am getting the following error:
from airtravel import *
a = Aircraft("G-EUPT", "Airbus A319", num_rows=22, num_seats_per_row=6)
Error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Aircraft' is not defined
Code:
class Flight:
def __init__(self, number):
if not number[:2].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:2].isupper():
raise ValueError("Invalid route number '{}'".format(number))
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError("Invalid route number '{}'".format(number))
self._number = number
def number(self):
return self._number
def airline(self):
return self._number[:2]
class Aircraft:
def __init__(self, registration, model, num_rows, num_seats_per_row):
self._registration = registration
self._model = model
self._num_rows = num_rows
self._num_seats_per_row = num_seats_per_row
def registration(self):
return self._registration
def model(self):
return self._model
def seating_plan(self):
return(range(1, self._num_rows + 1),
"ABCDEFGHJK"[:self._num_seats_per_row])
Where am I going wrong? Kindly help me understand. Why am I receiving this error?
I plan to execute the command a.Registration to get G-EUPT as the output.
this is a basic question in python for the new ,the python searchs for file path,
I guess the airtravel is that you create .PY(airtravel.py) file in your folder
like this:
and you will get the answer:
and if you learn more about import python file ,you can look here.
the import in python
from airtravel import (Aircraft, Flight)

Don't understand why this TypeError occurs when attempting to call inherited method

First, I am using python 3.6.
I am trying import and use my own .py file in my project. I import my LinkedList.py file and create a Mylist class, which extends the imported file's class.
When I try the construct an instance of the Mylist class, which involves creating an instance of my inheritedLinkedList derived class, I get the following error:
Traceback (most recent call last):
File "*/PycharmProjects/Veri Yapilari/lists.py", line 65, in <module>
test = Mylist()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 38, in __init__
self.linkedlist = inheritedLinkedList()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 8, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
Here's the section of the code where the problem occurs:
test = Mylist()
test.insertFirstM(incomingDataM=4) # <- Causes a TypeError.
Below is the main script in its entirety:
import LinkedList as myLinkedList
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super.__init__()
def raplaceElements(self, dataToBeChanged, incomingData):
position = self.find(dataToBeChanged)
position.data = incomingData
def swapElements(self, swap1, swap2):
position1 = self.find(swap1)
prev1 = position1.previous
next1 = position1.next
position2 = self.find(swap2)
prev2 = position2.previous
next2 = position2.next
prev1.next = position1
position1.previous = prev1
position1.next = next1
next1.previous = position1
prev2.next = position2
position2.previous = prev2
position2.next = next2
next2.previous = position2
def insertBefore(self, incomingData, previousNode=None):
self.insert(incomingData, self.find(previousNode).previous.data)
class Mylist:
def __init__(self):
# self.linkedlist = inheritedLinkedList;
self.linkedlist = inheritedLinkedList() # Per martineau's suggestion.
def replaceElements(self, dataToBeChanged, incomingData):
self.linkedlist.raplaceElements(dataToBeChanged, incomingData)
def swapElements(self, swap1, swap2):
self.linkedlist.swapElements(swap1, swap2)
def insertFirstM(self, incomingDataM):
self.linkedlist.insertFirst(incomingDataM)
def insertLast(self, incomingData):
self.linkedlist.insert(incomingData)
def insertAfter(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def insertBefore(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def remove(self, incomingData):
self.linkedlist.remove(incomingData)
def listprint(self):
self.linkedlist.listprint()
test = Mylist()
test.insertFirstM(4)
The code for the imported LinkedList module (LinkedList.py) can be obtained—if needed—by downloading it from my github repository.
As I said in a comment, you're not using the super built-in correctly. Try do things this way instead (so it's like the example in the linked documentation):
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super().__init__() # Change line to this.
Actually, since the derived class' __init__() is currently doing nothing but that, it's not even necessary because that's what would occur automatically if the subclass didn't define its own. In other words, the following would accomplish the same thing:
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
# ** NOT REALLY NEEDED AT ALL **
# def __init__(self):
# super().__init__()
P.S. You also ought to change the very end of the LinkedList.py script so the last few lines that are there don't execute when it's imported as a module by lists.py:
...
nextNode.previous = previousNode
dataToBeDeleted.next = dataToBeDeleted.previous = None
if __name__ == '__main__': # Should add this, too.
list1 = SinglyLinkedList()
list2 = DoublyLinkedList()
list2.insertFirst(6)

TypeError: 'tuple' object is not callable when trying to call method

Here is what I have going on so far:
# -*- coding: cp1252 -*-
import time
class Item():
def __init__(self, name, description, base_value):
self.name = name
self.description = description
self.ingredients = ingredients
self.base_value = value
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value)
class Metal(Item):
def __init__(self, name, description, ingredients, base_value):
self.smelt_time = smelt_time
self.smelted = smelted
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value, self.smelt_time, self.smelted)
class Bronze_Ingot(Metal):
def __init__(self):
self.name = "Bronze Ingot",
self.description = "A refined ingot of bronze."
#self.ingredients = Tin_Ore(1)+Copper_Ore(1) <--- I will get these lines working later...
self.base_value = 33
self.smelt_time = 15
self.smelted = ()
class Fuel(Item):
def __init__(self, name, description, ingredients, base_value):
self.fuel_time = fuel_time
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value, self.fuel_time)
class Cloth(Fuel):
def __init__(self):
self.name = "Cloth",
self.description = "A piece of cotton cloth."
#self.ingredients = 2 Cotton <--- I will get these lines working later...
self.base_value = 2
self.fuel_time = 5
But I am having great trouble with this function...
def smelted(Fuel, Metal):
if (Fuel.fuel_time - Metal.smelt_time) > 0:
time.sleep(1)
print "Smelting", Metal.name, "..."
time.sleep(Metal.smelt_time)
print "Time to forge!"
The problem is more or less making it work. My friend and I have tried EVERYTHING that we can think of when running this function, but to no avail. Here is our most recent attempt:
from Smelting_Progress import *
x = Cloth()
y = Bronze_Ingot()
y.smelted(x,y)
After trying to run this, I received this error:
Traceback (most recent call last):
File "C:\Users\WCS-HSSTUDENT\Desktop\Files\Project SAOffline\Coding\New Aincrad World\Items\NAI_Smelted.pyw", line 6, in <module>
Metal.smelted(Fuel, Metal)
TypeError: 'tuple' object is not callable
You have an instance attribute smelted; you set it in Metal.__init__():
self.smelted = smelted
Your Bronze_Ingot subclass sets it to an empty tuple:
self.smelted = ()
You cannot have both a method and and a tuple use the same name. Rename one or the other.
If you meant to use your smelted() code as a function, then define it at the top level (same indentation as your classes), and call it as a function, not a method:
smelted(x, y)
(note, no y. in front).

How could I import a class from a python script into another python script?

I am trying to write a script contains some classes and save for example as model.py.
import numpy as np
from scipy import integrate
class Cosmology(object):
def __init__(self, omega_m=0.3, omega_lam=0.7):
# no quintessence, no radiation in this universe!
self.omega_m = omega_m
self.omega_lam = omega_lam
self.omega_c = (1. - omega_m - omega_lam)
#self.omega_r = 0
def a(self, z):
return 1./(1+z)
def E(self, a):
return (self.omega_m*a**(-3) + self.omega_c*a**(-2) + self.omega_lam)**0.5
def __angKernel(self, x):
return self.E(x**-1)**-1
def Da(self, z, z_ref=0):
if isinstance(z, np.ndarray):
da = np.zeros_like(z)
for i in range(len(da)):
da[i] = self.Da(z[i], z_ref)
return da
else:
if z < 0:
raise ValueError(" z is negative")
if z < z_ref:
raise ValueError(" z should not not be smaller than the reference redshift")
d = integrate.quad(self.__angKernel, z_ref+1, z+1,epsrel=1.e-6, epsabs=1.e-12)
rk = (abs(self.omega_c))**0.5
if (rk*d > 0.01):
if self.omega_c > 0:
d = sinh(rk*d)/rk
if self.omega_c < 0:
d = sin(rk*d)/rk
return d/(1+z)
Then I want to call Cosmology class into another script, but I get the following error:
>>>from model import Cosmology as cosmo
>>>print cosmo.a(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method a() must be called with Cosmology instance as first argument (got int instance instead)
I don't quite understand what the problem is!! Any tips??
You are trying to call an instance method from a class. In order to use the a() method, you need to create an instance of the Cosmology class:
>>>from model import Cosmology
>>>cosmo = Cosmology()
>>>cosmo.a(1.)
0.5
Or, if you want a() to be a class method, you need to decorate it with the #classmethod decorator - see here for more details.

problem with inheritance in python

in school we got this class file:
class Konto:
def __init__(self, nummer):
self.__nr = nummer
self.__stand = 0
self.__minimum = -1000.0
def getStand(self):
return self.__stand
def getNr(self):
return self.__nr
def einzahlen(self, betrag):
self.__stand = self.__stand + betrag
def auszahlen(self, betrag):
if self.__stand - betrag >= self.__minimum:
self.__stand = self.__stand - betrag
else:
print("Auszahlung nicht möglich!")
class Sparkonto(Konto):
def __init__(self, nummer):
Konto.__init__(self, nummer)
self.__zinssatz = None
self.__minimum = 0
self.__maxAuszahlung = 2000.0
def setZinssatz(self, zinssatz):
self.__zinssatz = zinssatz
def getZinssatz(self):
return self.__zinssatz
def auszahlen(self, betrag):
if betrag <= self.__maxAuszahlung:
Konto.auszahlen(self, betrag)
else:
print("Auszahlung nicht möglich!")
def zinsenGutschreiben(self):
zinsen = self.__stand * (self.__zinssatz / 100)
self.einzahlen(zinsen)
When I run this test programm:
#Test
from sparkonto import *
s = Sparkonto(1)
s.einzahlen(1000)
print(s.getStand())
s.setZinssatz(4)
print(s.getZinssatz())
s.zinsenGutschreiben()
print(s.getStand())
s.auszahlen(2500)
print(s.getStand())
I get this error
1000
4
Traceback (most recent call last):
File "/home/malte/home/py3/sparkonto/test.py", line 8, in <module>
s.zinsenGutschreiben()
File "/home/malte/home/py3/sparkonto/sparkonto.py", line 44, in zinsenGutschreiben
AttributeError: 'Sparkonto' object has no attribute '_Sparkonto__einzahlen'
>>>
We do not know what we are doing wrong. Any guess?
Daniel was halfway there, you do need to change self.__einzahlen -> self.einzaheln, as he said.
Also, self.__stand belongs to the parent class. With the double underscore in the name, it gets mangled used anywhere else. But you don't need to use self.__stand directly. Konto gives you getStand().
Try something like this:
def zinsenGutschreiben(self):
zinsen = self.getStand() * (self.__zinssatz / 100)
self.einzahlen(zinsen)
self.__einzahlen(zinsen) -> self.einzahlen(zinsen)
Double leading underscores invoke name mangling, using the current class's name. Use a single leading underscore instead.

Categories

Resources