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.
Related
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)
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.
Ive made these classes below and I'm trying to have a tile in the game present a text based on an attribute in another class. I keep getting this error.
File "C:\Users\xxxxxxxx\PycharmProjects\Game.idea\Girls.py", line 20, in not_interested
return (self.interest < 10)
AttributeError: 'GirlTile' object has no attribute 'interest'
class Girls():
def __init__(self):
self.girlnames = ["Lucy", "Cindy", "April", "Allison", "Heather", "Andrea", "Brittany", "Jessica", "Lane", "Lauren", "Sabrina","Chelsea","Amber"]
self.name = random.choice(self.girlnames)
self.height = random.randrange(60, 72)
self.age = random.randrange(18, 25)
self.number = self.new_number()
self.interest = 0
def not_interested(self):
return (self.interest < 10)
from Girls import Girls
class GirlTile(MapTile):
def __init__(self,x,y):
self.enemy = Girls()
super().__init__(x, y)
def intro_text(self):
self.stance = Girls.not_interested(self)
if self.stance:
print("Hey whats up")
It looks like not_interested is an instance-level method, but you are trying to call it with a class (Girls). And the call is sort of "working" because you are passing the GirlTile instance in the call -- hence the error that the GirlTile has no interest attribute (because it does not).
Maybe you intended this instead?
def intro_text(self):
# Use an actual Girl instance to call not_interested().
self.stance = self.enemy.not_interested()
...
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).
Here's the error that I'm getting:
Running...done.
Traceback (most recent call last):
File "main.py", line 13, in <module>
print('Alice:\n Net pay: $%7.2f' % alice.calculate_pay())
TypeError: a float is required
Weird error, that I have no idea on what to do. I'm obviously beginning with Python, and thus far bug tracking has been easy, minus this. Here's the code below:
class Employee:
def __init__(self):
self.wage = 0
self.hours_worked = 0
def calculate_pay(self):
self.calculate_pay = (self.wage * self.hours_worked)
alice = Employee()
alice.wage = 9.25
alice.hours_worked = 35
print('Alice:\n Net pay: $%7.2f' % alice.calculate_pay())
bob = Employee()
bob.wage = 11.50
bob.hours_worked = 20
print('Bob:\n Net pay: $%7.2f' % bob.calculate_pay())
You're missing the return statement:
def calculate_pay(self):
self.calculate_pay = (self.wage * self.hours_worked)
return self.calculate_pay
You are calling calculate_pay method and its not returning anything, means it return None by default.
Please return value from function and use it or use variable instead or method
Variable Use
alice.calculate_pay()
print('Alice:\n Net pay: $%7.2f' % alice.calculate_pay)
OR
Return from function
def calculate_pay(self):
return (self.wage * self.hours_worked)
Change
def calculate_pay(self):
self.calculate_pay = (self.wage * self.hours_worked)
to
def calculate_pay(self):
self.calculate_pay = (self.wage * self.hours_worked)
return self.calculate_pay
The initial one is not callable and equals NoneType. Even though the value stored to self.calculate_pay is float you cannot reference it like that.
Change the method and instance variable to different names, and make return statment in your calculate_pay method:
def calculate_pay(self):
self.calculated_pay = (self.wage * self.hours_worked)
return self.calculated_pay