Python Class calling one function to another - python

I have just started OOPS and am completely new to it. I have a very basic question regarding the different ways I can call a function within another function in same class.
class StuffAnimal:
def __init__(self,name,color,weight,issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
self.situation = " "
def standup (self):
if self.issitting == True :
print("the stuff toy is sitting")
return "sit"
else :
print ("the stuff toy is not sitting")
return "notsit"
def move_teddy (self):
self.situation = standup(self.issitting)
if self.situation == 'sit' :
print ("teddy is not in the situation to move please change issitting to True")
elif self.situation == 'notsit' :
print ("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ",self.x,self.y)
but when i tried to call the function I got the following error.
teddy.move_teddy()
NameError: name 'standup' is not defined
This doesn't works. Can someone explain where did I go wrong.
Thank you.

As the method definition tells the method def standup(self)
is a instance method, (because of self)
does not accept parameters (because there is only self)
So the good way to cal it is
self.situation = self.standup()
Regarding the name of your methods, I'd say standup should set issitting to False, and define a sitdown method. Then the code of move_teddy would be more logic
class StuffAnimal:
def __init__(self, name, color, weight, issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
def standup(self):
self.issitting = False
print("the stuff toy is now up")
def sitdown(self):
self.issitting = True
print("the stuff toy is now sit")
def move_teddy(self):
if self.issitting:
print("teddy is not in the situation to move please change issitting to True")
else:
print("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ", self.x, self.y)
teddy = StuffAnimal("teddy", "black", 20, True)
teddy.move_teddy()
teddy.standup()
teddy.move_teddy()
teddy is not in the situation to move please change issitting to True
the stuff toy is now up
teddy is in the situation to move please give cordinates
x cordinates : 12
y cordinates : 34
teddy moved to 12 34

self parameter doesn't require to be called, and when you call a function from a class in the same class, your self. prefix !
class StuffAnimal:
def __init__(self,name,color,weight,issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
self.situation = " "
def standup (self):
if self.issitting == True :
print("the stuff toy is sitting")
return "sit"
else :
print ("the stuff toy is not sitting")
return "notsit"
def move_teddy (self):
self.situation = self.standup()
if self.situation == 'sit' :
print ("teddy is not in the situation to move please change issitting to True")
elif self.situation == 'notsit' :
print ("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ",self.x,self.y)

Related

how's i can calling to int from def in class?

i have this code:
class PLAYER:
def player_move(self):
if self.new_block == True:
body_copy = self.body[:]
body_copy.insert(0,body_copy[0] + self.direction)
self.body = body_copy[:]
self.new_block = False
self.score += 1
#print(self.score)
i want to calling self.score from outside the PLAYER class
You need to add a constructor (the init method) as done below, and within the constructor you must define self.score, as well as all the other fields you want your PLAYER class to have. In the code below I am assuming that when you are initializing a PLAYER object that you are providing the new_block, direction, and body information, however you defined these fields, which is unclear from the question.
class PLAYER:
def __init__(self, new_block,direction,body):
self.score = 0
self.new_block = new_block
self.direction = direction
self.body = body
def player_move(self):
if self.new_block == True:
body_copy = self.body[:]
body_copy.insert(0,body_copy[0] + self.direction)
self.body = body_copy[:]
self.new_block = False
self.score += 1

Python Inheritance error (with private variables)

I'm a beginner at coding and tried looking up the error but could not find why it showed up. Could someone please explain it to me?
My code as follows is:
class Automobile:
__material = None
__height = None
__width = None
__engine_size = None
def set_values(self, mat, height, width, engsz="M"):
self.__material = mat
self.__height = height
self.__width = width
self.__engine_size = engsz
def getMat(self):
return self.__material
def getHeight(self):
return self.__height
def getWidth(self):
return self.__width
def getEngineSize(self):
return self.__engine_size
class Car(Automobile):
__pricePU = None
def __findPricePerUnit(self):
return priceDict[self.getMat]
def price(self):
return self.getWidth * self.getHeight * self.__findPricePerUnit
print("A new car is being made")
print("What are the dimensions wanted for the new car in")
mat = input("Enter material: ")
height = input("Enter height: ")
width = input("Enter width: ")
car1 = Car()
car1.set_values(mat, height, width)
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price)
My input for this is:
iron=10,steel=20,gold=50,diamond=100
gold
1.5
5
The OUTPUT shown at the end is:
A new car has been made!
The price of this new car is:
<bound method Car.price of <__main__.Car object at 0x0000025DE7E84C70>>
I am not exactly sure why this is coming up, could someone please explain this to me!
There are several errors in the code, some of which are as follows:
On the last line, you should execute the price function like this car1.price()
In the price function, you should execute the functions instead of multiplying the pointers of the functions, like this:
def price(self):
return self.getWidth() * self.getHeight() * self.__findPricePerUnit()
There is no priceDict, so there will be an error in __findPricePerUnit as well.
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price())
Because price() is a method.

automatically instantiating objects

players_list = [Ani, Paty, Felix, Alex]
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.vote = 0
self.player_hand = []
self.choice = ''
self.player_hand = []
def player_turn(self):
print(self.name, "'s turn")
def p_vote(self):
print(self.name, " voted")
I tried to iterate over the list, but it always gives me an error: NameError: name 'Ani' is not defined
for player in players_list:
player = Player(str(player))
But doing all the process manually work:
Ani = Player("Ani"), etc
Is there any way that i can automate this process?
First of all the thing you should know, the players_list that you have declared are not containing strings, they are being considered as variables which you have not defined anywhere, and therefore the NameError.
Now, if you want to correct this, and if you actually intend to store objects of Player in players_list, then you can do the following:
players_list = ["Ani", "Paty", "Felix", "Alex"]
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.vote = 0
self.player_hand = []
self.choice = ''
self.player_hand = []
def player_turn(self):
print(self.name, "'s turn")
def p_vote(self):
print(self.name, " voted")
for i in range(len(players_list)):
players_list[i]=Player(players_list[i])
This will store Player objects in the list you have declared just the thing that you expect to get.
You are having problems with the players not being defined. So players_list = [Ani, Paty, Felix, Alex] will throw an error because the objects Ani, Paty, Felizx, and Alex do not exist.
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.vote = 0
self.player_hand = []
self.choice = ''
self.player_hand = []
def player_turn(self):
print(self.name, "'s turn")
def p_vote(self):
print(self.name, " voted")
Now, we need to iterate through the list.
players_list = ['Ani', 'Paty', 'Felix', 'Alex']
players = [Player(player) for player in players_list]
Sounds like you're trying to dynamically create variables - write code that writes code.
You could try to use the exec built-in function.
players = ['Ani', 'Paty', 'Felix', 'Alex']
class Player:
def __init__(self, name):
self.name = name
def p_vote(self):
print(self.name + " voted.")
for player in players:
exec( "%s = Player( '%s' )" %(player, player) )
Ani.p_vote()
Although, general internet advice has two points to make:
Be cautious where you use exec.
The Pythonic way is to write out the variables, "explicit is better than implicit."

I have a bad input error in python, any ideas how to fix it?

I have this bad error in put for a game I'm trying to code. It's bare bones at the moment, and I'm trying to code the information for one of the enemies the player fights.
class Enemy():
def __init__(self):
super(). __init__ (
self.name = "Goblin" +
self.healthpoints = 12 + # on this line
self.damage = 3)
def isAlive(self):
return self.hp > 0
Do you mean to do this?
class Enemy():
def __init__(self):
self.name = "Goblin"
self.healthpoints = 12
self.damage = 3
super().__init__(name=self.name, healthpoints=self.healthpoints, damage=self.damage)
enter code here
def isAlive(self):
return self.hp > 0
```
self.name = "Goblin" + is a syntax error. You aren't adding anything to "Goblin". The reason it is complaining about the line after is that it is trying to add self.healthpoints = 12 to "Goblin" and you can't add assignment statements.
I think what you want to do is something like this:
def __init__(self):
self.name = "Goblin"
self.healthpoints = 12
self.damage = 3

using a variable from a class in python

I think this question has been asked before but I have not found an answer suited to my problem. I basically have a class for different characters, which each have a cost. When creating a character, I want to take their cost away from the players score.
Here is an example of a class:
class Assassin(pygame.sprite.Sprite):
def __init__(self, x, y, row, column):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assassin.png")
self.x = x
self.type = "assassin"
self.y = y
self.rect = self.image.get_rect(center=(self.x, self.y))
self.damage = 60
self.health = 40
self.speed = 2
self.move = False
self.cost = 4
self.row = row
self.column = column
And here is the code where I would want to use the variable:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column ==1:
team1.add(Assassin(block.team1[0], block.team1[1], block.row, block.column))
block.team1Taken = True
score -= Assassin.__init__.cost #Example of what I think you would do
break
I hope I have explained this well enough to understand what I want.
You can't call score -= Assassin.__init__.cost in python.
The init method is the constructor of the Class and should be used to do so.
The value that you want is inside the object that you created, so you could call assassin.cost directly, assuming that assassin is the object.
So, you just need to change to:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column ==1:
current_assassin = Assassin(block.team1[0], block.team1[1], block.row, block.column)
team1.add(current_assassin)
block.team1Taken = True
score -= current_assassin.cost
break
You will need to keep a reference to the Assassin instance you create and then access its cost attribute:
if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
for block in blockGroup:
if block.team1Taken == False and block.column == 1:
new_assassin = Assassin(block.team1[0], block.team1[1],
block.row, block.column)
team1.add(new_assassin)
block.team1Taken = True
score -= new_assassin.cost
break

Categories

Resources