Modifying an Attribute's value through method - python

class UniversityAthletics():
def __init__(self, university_name, sport):
self.name = university_name
self.sport = sport
self.tickets_sold = 10
def tickets_sold(self):
"""This just tells you how many tickets have been sold"""
print(str(self.tickets_sold) + " tickets have been sold")
def describe_athletics(self):
print(self.name.title() + " " + self.sport.title())
def in_season(self):
print(self.sport.title() + " is in season.")
def set_tickets_sold(self, numticket):
"""This sets the number of tickets that have been sold"""
self.tickets_sold = numticket
def increment_tickets_sold(self, moretickets):
"""This increments the number of tickets sold"""
self.tickets_sold += moretickets
athletics = UniversityAthletics('salisbury university', 'soccer')
athletics.set_tickets_sold(20)
athletics.tickets_sold()
athletics.increment_tickets_sold(500)
athletics.tickets_sold()
I tried to make an attribute that sets the number of tickets sold 'set_tickets_sold' and then an attribute that changes the number of the tickets 'increment_tickets_sold' but when I try to set the number of tickets and then call the method 'tickets_sold()' i keep receiving an error.
Traceback (most recent call last): File
"E:/WorWic/IntroToProgramming/chapter9/University Athletics part
2.py", line 29, in
athletics.tickets_sold() TypeError: 'int' object is not callable
What did I do wrong?

Your issue is that tickets_sold is both an attribute and a function name. It's getting the attribute and calling that, rather than the function. I suggest renaming your function to something else.

Related

AttributeError: class object has no attribute

I am new to python. I try to access the attribute acnt_amount from the class bank_Customer, but throws "AttributeError" error. How to access the attribute of the function getDetails to withdraw with in the class from one function to another function? What is the mistake that i do? Any help will be much appreciated! Thanks in advance!
Code:
class bank_Customer:
def getDetails(self, cname, acnt_no, acnt_type, acnt_amount):
self.cname = cname
self.acnt_no = acnt_no
self.acnt_type = acnt_type
self.acnt_amount = acnt_amount
row = self.cname + "," + str(self.acnt_no) + "," + self.acnt_type + "," + str(self.acnt_amount) + "\n"
file = open('cust_details.csv','a')
file.write(str(row))
file.close()
print('*'*40)
print("Account has been added successfully!")
return self.acnt_amount
def withdraw(self):
cash = int(input("Please enter the amount to be withdrawn: "))
self.acnt_amount = self.acnt_amount - cash
f"balance amount is {balance}"
return balance
base = bank_Customer()
base.withdraw()
Error:
Traceback (most recent call last):
File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 96, in <module>
base.withdraw()
File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 66, in withdraw
self.acnt_amount = self.acnt_amount - cash
AttributeError: 'bank_Customer' object has no attribute 'acnt_amount'
As suggested, an init is required. Also consider setting up some defaults, and look at the use of "getters and setters".
You may gain some insight from the following sample bank account class that I wrote some time ago as an example.
# #Author:srattigan
# #Date:2020-12-10 11:10:33
# #LastModifiedBy:srattigan
# #Last Modified time:2020-12-14 09:50:13
# demo class for inheritance
class BankAccount:
"""Generic Bank Account
"""
acc_num = 100000
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.account_num = self.acc_num
BankAccount.acc_num += 1
def deposit(self, amount):
assert amount > 0, ValueError("Must deposit a positive amount")
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def __str__(self):
rep = f"Bankaccount for {self.name}"
rep += f"\n\tAcc Num: {self.account_num}"
rep += f"\n\tBalance: €{self.balance:.2f}"
return rep
customer = BankAccount("Fred Jones", 99)
print(customer)
You need to def init as your first method. Thats where you specify cname, acnt_no etc.
you need to declare the variables inside the class first.
create the init() constructor to declare and initialize those variables

Trying to change certain values in objects while using file access

I'm trying to change a specific part of an object. Specifically, I'm trying to subtract a certain value from the acc. Where then the change is recorded on an already created text file.
Traceback (most recent call last):
File "main.py", line 152, in <module>
start()
File "main.py", line 141, in start
withdraw(id,input("How much do you want to withdraw?"))
File "main.py", line 55, in withdraw
if allCustom[d].hkid== x:
TypeError: list indices must be integers or slices, not Customer
class Customer:
def __init__(self, name, date, address, hkid, acc):
self.name = name
self.date = date
self.address = address
self.hkid = hkid
self.acc = acc
allCustom = [customer1, customer2, customer3, customer4, customer5]
customer1 = Customer ("Sarah Parker","1/1/2000","Hong Kong, Tai Koo,Tai Koo Shing Block 22,Floor 10, Flat 1", "X1343434","2222")
def withdraw (x,y):
global allCustom
count = 0
for d in allCustom:
if allCustom[d].hkid== x:
if int(allCustom[d].acc) >= int(y):
allCustom[d] = Customer (allCustom[d].name, allCustom[d].date, allCustom[d].address, allCustom[d].hkid, str(int(allCustom[d].acc)-int(y)))
print("Success! Please collect your money.")
break
else:
print("Sorry but you have inseffecient funds to withdraw $"+y)
elif count == len(allCustom):
print("Your HKID does not match any account in our database. Returning to starting screen")
else:
count +=1
def UpdateFile():
global allCustom
OutFile=open("CustomInfo.txt", "w")
for c in allCustom:
OutFile.write(f"\nName:{c.name}\n")
OutFile.write(f"Birth Date:{c.date}\n")
OutFile.write(f"Address:{c.address}\n")
OutFile.write(f"HKID:{c.hkid}\n")
OutFile.write(f"Account value:{c.acc}\n")
OutFile.close()
UpdateFile()
As #furas said in a comment, just use:
if d.hkid== x:
This is because for d in allCustom: will iterate over the list allCustom binding the variable d to each item of the list in turn. At this point d is a Customer object and you can access its attributes. You therefore do not need to try to lookup the customer in the list because you already have a reference to it in d.
You will need to correct the other instances of allCustom[d] in the rest of your code.
You probably have this confused because of this Python idiom:
for i in range(len(allCustom)):
if allCustom[i].hkid== x:
which uses indices to access the items in the list. The first form for d in allCustom is preferred - it is clearer and more succinct.

Trouble Creating Instance of Class

I have the code below, but I am getting an error when I try to create an instance of the class.
class Flight():
def __init__(self, capacity):
self.capacity = capacity
self.passengers = []
def add_passenger(self, name):
if not self.open_seats():
return False
self.passengers.append(name)
return True
def open_seats(self):
return self.capacity - len(self.passengers)
f = Flight(3)
people = ["Aicel", "Angela", "Randy", "Monina"]
for person in people:
success = flight.add_passengers(person)
if success:
print(f"Added {person} to flight successfully")
else:
print(f"No available seats for {person}")
This the error message:
Traceback (most recent call last):
File classflight.py Line 19, in <module>
success = flight.add_passenger(person)
NameError: name 'flight' is not defined
The error message tells you: name 'flight' is not defined.
If you look closer at the line in question from the error message (success = flight.add_passenger(person)) and the rest of your code, you see that the Flight instance that you created is not named flight but f. So to make your code work,
either change f = Flight(3) to flight = Flight(3)
or change success = flight.add_passenger(person) to success = f.add_passenger(person)

Why doesn't Python see a specified int() attribute?

I am building a Python-based, single-player, word-based, MMORPG game. I am a beginner and wish this to be a simple task. I have coded the moving part, in which the character moves from one site to another. It seems to not work, as Python seems to not be able to see my attributes. This is the error message:
Traceback (most recent call last):
File "C:/Users/lenovo/Desktop/Maelstrom/Maelstrom Move.py", line 51, in
place = test.place
AttributeError: 'Player' object has no attribute 'place'
This is my code:
class Player(object):
"""The player."""
def __init__(self,name="name",inv=[],equip=[],stats=[],place=int("001"),knownplaces={}):
self.name = input("What name do you want?")
knownplaces[int("001")]="Ruby City"
knownplaces[int("002")]="Ruby Inn"
knownplaces[int("003")]="Ruby Forests"
knownplaces[int("004")]="Ruby Countryside"
knownplaces[int("005")]="Witch Hideout"
def __str__():
rep = self.movepossible
def movepossible(self,position):
#001--Ruby City
#002--Ruby Inn
#003--Ruby Forests
#004--Ruby Countryside
#005--Witch Hideout
if position==int("001"):
possible=[int("002"),int("003")]
return possible
elif position==int("002"):
possible=[int("001")]
return possible
elif position==int("003"):
possible=[int("001"),int("004")]
return possible
elif position==int("004"):
possible=[int("001"),int("003"),int("005")]
return possible
elif position==int("005"):
possible=[int("004")]
return possible
else:
return null
def move(self,position):
possiblewords=[]
print('Choose between paths:'/n)
possible = movepossible(self, position)
for m in range(0,len(possible),1):
possiblewords.append(knownplaces[possible[m]])
for n in range(0,len(possiblewords),1):
print(m+':'+possiblewords[m-1] /n)
choice=input('Make your choice...')
if choice-1 <= len(possiblewords):
self.place=possible[choice-1]
def showposition(self):
print(knownplaces[self.place])
test = Player()
while True:
place = test.place
test.move(place)
test.showposition()
At the time the line place = test.place is executed, the place attribute on your Player instance has not been defined.
The first time the place attribute gets set is in the move() method. i.e. Attempting to access place before calling move() will result in the error you are observing.
You should assign a default value to self.place in the initializer for the Player class.

Class Attribute is clearly there, but python cant find it

Why am i getting this attribute error?
class GameState(object):
"""Keeps track game state variables"""
def __init__(self, convo_flag=0, characters_talked_to=0, convo_log=(None)):
self.convo_flag = convo_flag
self.characters_talked_to = characters_talked_to
self.convo_log = convo_log
def welcome_screen():
global LAST_NAME
global BULLY
global DAY
raw_input(messages.WELCOME)
LAST_NAME = raw_input(messages.LAST_NAME)
BULLY = characters.random_character(cclass='Camper', gender='m')
print 'Your name is Pickett %s' % LAST_NAME
messages.print_messages([
messages.EXPLANATION,
messages.BUS_LOADING,
messages.CRACK,
messages.GAME_KID_LOST])
return week_one(DAY)
def week_one(day):
if day == 1:
messages.print_messages(messages.WEEK_ONE[day])
campers = characters.random_character_sample(cclass='Camper', count=5)
people_outside_theater = campers + [characters.TROID]
while GameState.characters_talked_to != 3:
I dont get why im getting this attribute error, i totally declared it in that constructor, is there something i am missing were i need to declare it outside the constructor? This is really racking my brain.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pickett.py", line 44, in welcome_screen
return week_one(DAY)
File "pickett.py", line 52, in week_one
while GameState.characters_talked_to != 3:
AttributeError: type object 'GameState' has no attribute 'characters_talked_to'
You need to create an instance in order you use your class like this:
gameState = GameState()
while gameState.characters_talked_to != 3:
In your code you were trying to access class-level attribute which is not defined in your class.
Your __init__ function sets characters_talked_to on self, which is an instance of GameState.
You did not set it on GameState, which is a class.
Neither did you create any instances of GameState, so in any case __init__ is never called by your program.

Categories