Python variable is not getting initialized with desired object, why? - python

So I am designing a battleship backend system that will be running on google apps engine... I just started yesterday and designed a framework for the game.
Unfortunately for me, I have not coded too much in python so I am not too familiar with the specifics of the language. I keep getting the following error when I try to run the program:
File "C:\Users\Shlomo\Desktop\eclipse\plugins\org.python.pydev_2.7.5.2013052819\pysrc\pydev_runfiles.py", line 432, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\Shlomo\workspace\battleship\Battleship.py", line 222, in <module>
battleship = BattleshipGame("Shlomo",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5,"John",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5)
File "C:\Users\Shlomo\workspace\battleship\Battleship.py", line 210, in __init__
field = self.player1_field.getField()
AttributeError: 'NoneType' object has no attribute 'getField'
ERROR: Module: Battleship could not be imported (file: C:\Users\Shlomo\workspace\battleship\Battleship.py).
So I translated this error as the variable field is not getting initialized with the PlayerField object...
Here is my code:
import random
class Player:
player_name = None
player_id = None
game_id = None
your_turn = False
player_field = None
hit_field = None
opponent = None
def __init__(self,name,player_field,hit_field,opponent):
self.player_name = name
self.player_field = player_field
self.hit_field = hit_field
self.opponent = opponent
def getPlayerField(self):
return self.player_field
def performHit(self,x,y):
mark = None
hit = self.opponent.getPlayerField.hitAt(x,y)
if hit:
mark = 'X'
else:
mark = 'O'
self.hit_field.markHitField(x,y,mark)
class HitField:
hit_field = None
def __init__(self):
hit_field = [[0 for i in xrange(10)] for i in xrange(10)]
def markHitField(self,x,y,mark):
self.hitfield[x][y] = mark
class PlayerField:
player_field = [[0 for i in xrange(10)] for i in xrange(10)]
shipsOnField = []
goodToGo = False
def __init__(self,battleship,aircraft,destroyer,submarine,patrol):
if self.validPlacement(battleship)and self.validPlacement(aircraft)and self.validPlacement(destroyer) and self.validPlacement(submarine) and self.validPlacement(patrol):
self.placeShip(battleship)
self.placeShip(aircraft)
self.placeShip(destroyer)
self.placeShip(submarine)
self.placeShip(patrol)
self.shipsOnField.append(battleship)
self.shipsOnField.append(aircraft)
self.shipsOnField.append(destroyer)
self.shipsOnField.append(submarine)
self.shipsOnField.append(patrol)
self.goodToGo = True
else:
print "some pieces have been placed incorrectly"
def validPlacement(self,ship):
hx = ship.getHeadX;
hy = ship.getHeadY;
tx = ship.getTailX;
ty = ship.getTailY;
if not hx > 0 and not hx < 11:
return False
return True
def placeShip(self,ship):
hx = ship.getHeadX();
hy = ship.getHeadY();
tx = ship.getTailX();
ty = ship.getTailY();
for y in range(ty,hy):
for x in range(tx,hx):
self.player_field[x][y] = ship.getShipID
def hitAt(self,x,y):
hitPos = self.player_field[x][y]
if not hitPos == 0 and not hitPos == 'X':
self.getShipByID(hitPos).removeHealth
self.player_field[x][y] = 'X'
return True
def getShipByID(self,ID):
for ship in self.shipsOnField:
if ship.getShipID == ID:
return ship
def getField(self):
return self.player_field
class Ship(object):
ship_id = None
ship_name = None
max_health = None
remaining_health = None
head_pos_x = None
head_pos_y = None
tail_pos_x = None
tail_pos_y = None
def __init__(self,id,name,max,hx,hy,tx,ty):
self.ship_id = id
self.max_health = max
self.remaining_health = max
self.ship_name = name
self.head_pos_x = hx
self.head_pos_y = hy
self.tail_pos_x = tx
self.tail_pos_y = ty
self.remaining_health = max
def removeHealth(self):
self.remaining_health -= 1
def getHeadX(self):
return self.head_pos_x
def getHeadY(self):
return self.head_pos_y
def getTailX(self):
return self.tail_pos_x
def getTailY(self):
return self.tail_pos_y
def getRemainingHealth(self):
return self.remaining_health
def getShipID(self):
return self.ship_id
class Battleship(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,1,"Battle Ship",4,hx,hy,tx,ty)
class AircraftCarrier(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,2,"Aircraft Carrier",5,hx,hy,tx,ty)
class Destroyer(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,3,"Destroyer",3,hx,hy,tx,ty)
class Submarine(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,4,"Submarine",3,hx,hy,tx,ty)
class PatrolBoat(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,5,"Patrol Boat",2,hx,hy,tx,ty)
class BattleshipGame:
current_turn = None
player1 = None
player2 = None
player1_field = None
player1_opponent = player2
player2_field = None
player2_opponent = player1
def firstTurn(self):
rand = random.randint(1,2)
if rand==1:
return self.player1
else:
return self.player2
def printGameBoard(self):
field = self.player1_field.getField()
for y in range(1,10):
for x in range(1,10):
print field[x][y]
print '\n'
def __init__(self,p1name,p1bshx,p1bshy,p1bstx,p1bsty
,p1dhx,p1dhy,p1dtx,p1dty
,p1shx,p1shy,p1stx,p1sty
,p1pbhx,p1pbhy,p1pbtx,p1pbty
,p1achx,p1achy,p1actx,p1acty
,p2name,p2bshx,p2bshy,p2bstx,p2bsty
,p2dhx,p2dhy,p2dtx,p2dty
,p2shx,p2shy,p2stx,p2sty
,p2pbhx,p2pbhy,p2pbtx,p2pbty
,p2achx,p2achy,p2actx,p2acty):
player1_field = PlayerField(Battleship(p1bshx,p1bshy,p1bstx,p1bsty),
AircraftCarrier(p1achx,p1achy,p1actx,p1acty),
Destroyer(p1dhx,p1dhy,p1dtx,p1dty),
Submarine(p1shx,p1shy,p1stx,p1sty),
PatrolBoat(p1pbhx,p1pbhy,p1pbtx,p1pbty))
player2_field = PlayerField(Battleship(p2bshx,p2bshy,p2bstx,p2bsty),
AircraftCarrier(p2achx,p2achy,p2actx,p2acty),
Destroyer(p2dhx,p2dhy,p2dtx,p2dty),
Submarine(p2shx,p2shy,p2stx,p2sty),
PatrolBoat(p2pbhx,p2pbhy,p2pbtx,p2pbty))
player1 = Player(p1name,self.player1_field,HitField(),self.player2)
player2 = Player(p2name,self.player2_field,HitField(),self.player1)
self.current_turn = self.firstTurn()
battleship = BattleshipGame("Player1",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5,"Player2",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5)
battleship.printGameBoard()
Sorry about the sytax, I had trouble pasting it in the code format. This code probably has a few problems but I have not been able to get passed this problem yet...
What am I doing wrong?

In your __init__, you're assigning to a local variable player1_field rather than to instance data. Instead of:
player1_field = PlayerField(...
You want:
self.player1_field = PlayerField(...
Without that, you're trying to deference your class's value for player1_field, which is None.

Python isn't Java or whatever language you are trying to write. These mutable class attributes are unlikely to do what you think they do.
class PlayerField:
player_field = [[0 for i in xrange(10)] for i in xrange(10)]
shipsOnField = []
goodToGo = False

Related

Why is my tripssincemaintenence output 1 instead of 99 in Python classes?

I am using Python 3. Here is what my class and inheritance class looks like:
class Vehicle:
def __init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False):
self.make = Make
self.model = Model
self.year = Year
self.weight = Weight
self.needsmaintenance = NeedsMaintenance
self.tripssincemaintenance = TripsSinceMaintenance
def repair(self):
self.needsmaintenance = True
self.tripssincemaintenance = 0
class Cars(Vehicle):
def __init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False,isdriving = False):
Vehicle.__init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False)
self.isDriving = isdriving
def Drive(self):
self.isDriving = True
def Stop(self):
self.isDriving = False
self.tripssincemaintenance += 1
if self.tripssincemaintenance == 100:
self.needsmaintenance = True
This is where I make use of the class:
Car2 = Cars("Mercedes","G-Wagon","2016","2000", 98,False)
Car2.Drive()
Car2.Stop()
print(Car2.year)
print(Car2.model)
print(Car2.make)
print(Car2.isDriving)
print(Car2.needsmaintenance)
print(Car2.tripssincemaintenance)
print(Car2.weight)
The problem is that when self.tripssincemaintenance is printed, it shows 1 instead of 99. Why is that? TIA

How to handle the TypeError: 'int' object is not callable?

I want to implements a-star algorithm and the function (from Route_Algorithm.py) extends the nodes to get the next layor of f_value in the tree . The node can be regard as the station. And the self.settings.station_matrix is the numpy.matrix.
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
However, when I run the part of code. It reports the error like this:
Traceback (most recent call last):
File "/home/surface/Final-Year-Project/FYP/Main.py", line 4, in <module>
class main():
File "/home/surface/Final-Year-Project/FYP/Main.py", line 13, in main
new_route.busy_route_matrix()
File "/home/surface/Final-Year-Project/FYP/oop_objects/Route.py", line 87, in busy_route_matrix
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 40, in A_STAR_Algorithm
self.voluation_station(successor, dest_location,bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 73, in voluation_station
station.get_g(self.settings.station_matrix[successor][end_element])
TypeError: 'int' object is not callable
I search the solution in the Internet, I think the problem may be in the end_element, maybe some inherient problem but I'm not sure. Can some one help me! Please!
Additional codes for other classes:
These classes are Util classes, which helps for handle oop_objects!
The class is for the Route_Algorithm:
from Util.Mergesort_algorithm import mergesort_algorithm
class route_algorithm():
'''generate the route to optimise the profiles'''
def __init__(self,settings):
# a* algorithm
self.open_list = []
self.close_list = []
self.route = []
self.settings = settings
self.flag_find = False
self.lines = []
# merge_sort algorithm
self.mergesort_algorithm = mergesort_algorithm()
def A_STAR_Algorithm(self, start_location, dest_location,bus_stations):
'''search the best route for each passenger to the destination'''
#self.clean_f(bus_stations)
# initial the value of f in start_location
for item in bus_stations:
if int(item.name) == start_location:
item.get_g = 0
for key, value in item.adjacent_station.items():
if int(key.name) == dest_location:
item.get_h = value
self.open_list.append(start_location)
#start_location is the name of station
while self.flag_find == False:
successor = self.open_list[0]
self.open_list.remove(successor)
self.route.append(successor)
self.voluation_station(successor, dest_location,bus_stations)
self.a_brain_judge_1(dest_location,bus_stations)
print(self.flag_find)
if self.flag_find == True:
#end the location
self.route.append(dest_location)
#add the line to the self.line
self.print_lines()
self.flag_find = False
self.open_list = []
else:
#continue to search the minimize
list = self.sort(bus_stations)
for item in list:
print(item.name)
print(item.f)
#疑问如果前两个的预估值一样该如何处理
self.open_list.append(int(list[0].name))
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
def a_brain_judge_1(self, dest_location,bus_stations):
'''whether the direct_line is the optimize'''
tmp_dest = bus_stations[0]
self.tmp_nodes = []
self.flag_find = True
for element in bus_stations:
if int(element.name) == dest_location:
tmp_dest = element
for element in bus_stations:
if element == tmp_dest:
pass
else:
if element.f < tmp_dest.f:
self.tmp_nodes.append(element)
self.flag_find = False
if self.flag_find == True:
self.route.append(tmp_dest.name)
return None
else:
return self.tmp_nodes
def sort(self,bus_stations):
'''sort all the f in the next stations'''
return self.mergesort_algorithm.Merge_Sort(bus_stations)
def print_lines(self):
#print(len(self.route))
for item in self.route:
print(item)
print("NEXT PASSENGER!---------")
def clean_f(self,stations):
for item in stations:
item.clean_data()
The class is Random_Algorithm, which helps for generate the random passengers.
import random
from Data.Settings import settings
from oop_objects.Bus_Station import bus_station
from oop_objects.Passenger import passenger
class random_algorithm():
'''generate the random bus-stations and passengers'''
def __init__(self):
self.setting = settings()
def random_passenger(self,number):
'''generate random passengers for bus-station,
and assumes there are 6 stations now. Furthermore, the data will be crawled by the creeper'''
passengers = []
for i in range(number):
new_passenger = passenger()
random.seed(self.setting.seed)
new_passenger.Change_Name(random.randint(1,self.setting.bus_station_number))
# generate the start-location
self.setting.seed +=1
end_location = random.randint(1,self.setting.bus_station_number)
# generate the end-location
while new_passenger.name == end_location:
self.setting.seed += 1
end_location = random.randint(1,self.setting.bus_station_number)
#judge whether the start-location same as the end-location
new_passenger.change_end_location(end_location)
passengers.append(new_passenger)
return passengers
def random_station(self,number):
'''generate the name of random stations '''
bus_stations = []
for i in range(number):
new_bus_station = bus_station()
new_bus_station.Name(str(i))
bus_stations.append(new_bus_station)
return bus_stations
def random_edge(self,bus_stations):
'''generate the edge information for the stations'''
for location1 in bus_stations:
#print("The information add in "+location1.name)
for location2 in bus_stations:
if location1 != location2:
#print("the "+location2.name+" was added in the "+location1.name)
if location2 not in location1.adjacent_station and location1 not in location2.adjacent_station:
random.seed(self.setting.seed)
edge = random.randint(1,self.setting.edge_distance)
location1.add_adjacent_station(location2,edge)
#print("the edge is "+str(edge))
self.setting.seed += 1
return bus_stations
The class is the mergesort_algorithm, which compare the f for different stations
class mergesort_algorithm():
def Merge_Sort(self,stations):
length = len(stations)
middle = int(length/2)
if length<=1:
return stations
else:
list1 = self.Merge_Sort(stations[:middle])
list2 = self.Merge_Sort(stations[middle:])
return self.Merge(list1,list2)
def Merge(self,list1,list2):
list3 = []
length1 = len(list1)
length2 = len(list2)
point1 = 0
point2 = 0
while point1<=length1-1 and point2<=length2-1:
if list1[point1].f<list2[point2].f:
list3.append(list1[point1])
point1 += 1
else:
list3.append(list2[point2])
point2 += 1
if point1>=length1:
for i in range(length2):
if i>=point2:
list3.append(list2[point2])
if point2>=length2:
for i in range(length1):
if i>=point1:
list3.append(list1[point1])
return list3
#def print_sort_result(self):
The following class are oop.classes
The class is for the Route:
from Util.Random_Algorithm import random_algorithm
from Data.Settings import settings
from Util.Route_Algorithm import route_algorithm
import numpy as np
class route():
def __init__(self):
self.bus_stations = []
self.passengers = []
self.settings = settings()
#random algorithm
self.random_algorithm = random_algorithm()
#route_algorithm
self.route_algorithm = route_algorithm(self.settings)
def start_route(self):
'''The raw route Information(TEXT) for bus_stations '''
stations = self.random_algorithm.random_station(self.settings.bus_station_number)
finsih_edge_stations = self.random_algorithm.random_edge(stations)
'''
for item in finsih_edge_stations:
print("\nthe information for " + item.name + " is: \t")
for key, value in item.adjacent_station.items():
print("the station is " + key.name)
print(" the distace is " + str(value))
'''
self.bus_stations = finsih_edge_stations
'''The raw route Information(Text) for passengers'''
self.passengers = self.random_algorithm.random_passenger(self.settings.passengers_number)
def bus_stations_matrix(self):
'''trasfer the raw text to the matrix'''
#create zero_matrix
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
station_matrix = tmp_matrix.reshape(length,length)
for item in self.bus_stations:
for key,value in item.adjacent_station.items():
station_matrix[int(item.name)][int(key.name)] = value
station_matrix[int(key.name)][int(item.name)] = value
print(station_matrix)
self.settings.station_matrix = station_matrix
def passengers_matrix(self):
'''trasfer the raw text to the matrix'''
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
passenger_matrix = tmp_matrix.reshape(length,length)
for item in self.passengers:
#print("the start location of passenger is "+str(item.name))
#print("the end location of passenger is "+str(item.end_location))
#print(" ")
passenger_matrix[item.name-1][item.end_location-1]+=1;
print(passenger_matrix)
self.settings.passenger_matrix = passenger_matrix
def busy_route_matrix(self):
'''generate the bus_busy_route matrix'''
#read the requirements of passengers
length = self.settings.bus_station_number
for start_location in range(length):
for dest_location in range(length):
if self.settings.passenger_matrix[start_location][dest_location] == 0:
pass
else:
magnitude = self.settings.passenger_matrix[start_location][dest_location]
#运行a*算法去寻找最短路径/run the a* algorithm to search the path
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
print("------------------------------------")
def practice(self):
'''practice some programming'''
for element in self.bus_stations:
print((element.f))
The class is for the Passenger
class passenger():
def __init__(self):
self.name = 0
self.end_location = "null"
def Change_Name(self,name):
'''change the name of passenger'''
self.name = name
def change_end_location(self,location):
'''generate the end_location'''
self.end_location = location
The class for the bus_station
class bus_station():
'''the class represents the bus station'''
def __init__(self):
'''the attribute of name means the name of bus-station
the attribute of passenger means the passenger now in the bus-station'''
self.name = "null"
self.passenger = []
self.adjacent_station = {}
#A* algorithm
self.g = 0
self.h = 0
self.f = 0
def Name(self,name):
'''change the name of the station'''
self.name = name
def add_passengers(self,*passenger):
'''add the passenger in the bus-station'''
self.passenger.append(passenger)
def add_adjacent_station(self,station,edge):
'''add the adjacent station in the this station'''
self.adjacent_station[station] = edge
def get_g(self,value):
'''get the value of g (线路值)'''
self.g =self.g+ value
def get_h(self,value):
'''get the value of f (预估值)'''
self.h = value
def result_f(self):
'''print the value of f (实际值)'''
self.f = self.g+self.h
def add_self_cost(self):
self.add_adjacent_station()
The following class is storing the data.
The class is for the setting:
class settings():
def __init__(self):
self.seed = 5
self.bus_station_number = 10
self.passengers_number = 10
self.edge_distance = 50
self.station_matrix = None
self.passenger_matrix = None
And the main class to run the whole project:
from oop_objects.Route import route
class main():
new_route = route()
new_route.start_route()
print("The distance between different bus station :")
new_route.bus_stations_matrix()
print("The location information for passengers :")
new_route.passengers_matrix()
new_route.busy_route_matrix()
#new_route.practice()practice
#new_route.sort()bus_stations
You should avoid the station of successor because you have assigned the value by using the get_g
The result should be:
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
if end_element == successor:
pass
else:
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations

How to alter a variable defined in a parent class in the child class without altering the parent class variable itself?

I'm trying to create two subclasses based on the same parent class, so that they each have their own versions of the same variables defined in the parent object. However I realized that changing these variables in one of these subclasses will cause the versions in the other subclass to change as well. I know I am probably not fully understanding the idea of Inheritance. Please help!
import random
class PlayerParent():
id = 1
# Cooperate: True; Betrayal: False
opponent_moves_history = {}
self_moves_history = {}
def append_opponent_history(self, round_num, c_true, misunderstand=0.0):
# randomly change the result based on probability given in misunderstand
random_num = random.uniform(0, 1)
if random_num <= misunderstand:
c_true = not c_true
self.opponent_moves_history[round_num] = c_true
def append_self_history(self, round_num, c_true, misunderstand=0.0):
# randomly change the result based on probability given in misunderstand
random_num = random.uniform(0, 1)
if random_num <= misunderstand:
c_true = not c_true
self.self_moves_history[round_num] = c_true
score = int(0)
def score_keeper(self, round_num):
if (self.opponent_moves_history[round_num] == True) and (self.self_moves_history[round_num] == False):
self.score += 7
if (self.opponent_moves_history[round_num] == True) and (self.self_moves_history[round_num] == True):
self.score += 5
if (self.opponent_moves_history[round_num] == False) and (self.self_moves_history[round_num] == True):
self.score += 1
if (self.opponent_moves_history[round_num] == False) and (self.self_moves_history[round_num] == False):
self.score += 2
def get_score(self):
return self.score
class TitForTat(PlayerParent):
def rule(self, round_num):
if len(self.opponent_moves_history) == 0:
return True
else:
return self.opponent_moves_history[round_num - 1]
class Random(PlayerParent):
def rule(self, round_num):
random_num = random.uniform(0, 1)
if random_num >= 0.5:
return True
else:
return False
Random = Random()
Random.id = 1
TitForTat = TitForTat()
TitForTat.id = 2
def match(a, b):
game_counter = 1
# while game_counter <= 10:
#a_result = a.rule(game_counter)
# b_result = b.rule(game_counter)
# print(a_result, b_result)
# a.append_self_history(game_counter, a_result)
# b.append_opponent_history(game_counter, a_result)
# b.append_self_history(game_counter, b_result)
# a.append_opponent_history(game_counter, b_result)
# a.score_keeper(game_counter)
# b.score_keeper(game_counter)
# game_counter += 1
# print(a.get_score(), b.get_score())
a.self_moves_history[1] = True
print(a.self_moves_history, '\n', b.self_moves_history)
match(Random, TitForTat)
Resulting a.self_moves_history and b.self_moves_history is identical even though no alteration has been done to the b class variable.
I commented out chunks of the codes just to test where went wrong.
You are making opponent_moves_history a class variable, so naturally any change to it is class-wide.
In your case you should make opponent_moves_history, along with self_moves_history and id instance variables instead, so that changes made to them are specific to the instances.
class PlayerParent():
def __init__(self):
self.id = 1
self.opponent_moves_history = {}
self.self_moves_history = {}

Getting Pylint E1101 - Instance has no such member

Pylint doesn't like this code:
class sequence(list):
def __init__(self, n):
list.__init__(self)
self += self._generate_collatz_seq(n)
self.pivots = self._generate_pivots()
self.data = self._make_data()
def _collatz_function(self, n):
if n % 2 == 0:
return(int(n/2))
else:
return(3*n + 1)
def _generate_collatz_seq(self, x):
int(x)
sequence_holder = []
while x != 1:
sequence_holder.append(x)
x = self._collatz_function(x)
sequence_holder.append(1)
return sequence_holder
def _generate_pivots(self):
pivots_holder = []
for element in self:
if element % 2 != 0:
pivots_holder.append(element)
return pivots_holder
def _make_data(self):
data_holder = []
data_holder.append(len(self))
data_holder.append(len(self.pivots))
return data_holder
It says
E1101: Instance of 'sequence' has no 'pivots' member(56,36)
This is before I have made any instances of sequence. I'm sure I haven't gone about my task in the most efficient way, but I can't see that I've done anything wrong.

Error: object() takes no parameters , cant resolve it

this is python file im trying to make A*algorithm , but cant get it to work, I need some help , its an awesome code , its been run in latest python version for windows
from queue import PriorityQueue
class State(object):
def _init_(self,value,parent,start = 0,goal = 0):
self.children = []
self.value = value
self.parent = parent
self.dist = 0
if parent:
self.path = parent.path[:]
self.path.append(value)
self.start = parent.start
self.goal = parent.goal
else:
self.path = [value]
self.start = start
self.goal = goal
def GetDist(self):
pass
def CreateChildren(self):
pass
class State_String(State):
def _init_(self,value,parent,start = 0,goal = 0):
super(State_String,self).__init__(value,parent,start,goal)
self.dist = self.GetDist()
def GetDist(self):
if self.value == self.goal:
return 0
dist = 0
for i in range(len(self.goal)):
letter = self.goal[i]
dist += abs(i - self.value.index(letter))
return dist
def CreateChildren(self):
if not self.children:
for i in xrange(len(self.goal)-1):
val = self.value
val = val[:i] + val[i+1] + val[i] + val[i+2:]
child = State_String(val,self)
self.children.append(child)
class AStar_Solver:
def _init_(self,start,goal):
self.path = []
self.visitedQueue = []
self.priorityQueue = PriorityQueue()
self.start = start
self.goal = goal
def Solve(self):
startState = State_String(self.start,0,self.start,self.goal)
count = 0
self.priorityQueue.put((0,count,startState))
while(not self.path and self.priorityQueue.qsize()):
closestChild = self.priorityQueue.get()[2]
closestChild.CreateChildren()
self.visitedQueue.append(closestChild.value)
for child in closestChild.children:
if child.value not in self.visitedQueue:
count +=1
if not child.dist:
self.path = child.path
break
self.priorityQueue.put((child.dist,count,child))
if not self.path:
print "Goal of " + self.goal + " is not possible!"
return self.path
if _name_ == '__main__':
start1 = "hma"
goal1 = "ham"
a = AStar_Solver(start1,goal1)
a.Solve()
for i in xrange(len(a.path)):
print " %d)" %i + a.path[i]
getting these errors:
Traceback (most recent call last):
File "C:/Users/Herby/Desktop/untitled/Astar.py", line 82, in <module>
a.Solve()
File "C:/Users/Herby/Desktop/untitled/Astar.py", line 59, in Solve
startState = State_String(self.start,0,self.start,self.goal)
TypeError: object() takes no parameters
I need to know how it can be fixed
All of your init in your classes are written with single underscore instead of double underscore:
Change all init written as: _init_ to __init__
Also, this line is incorrect as well:
if _name_ == '__main__':
It needs to be double underscore for name as well
if __name__ == '__main__':
If you're interested, here is more information on why this is needed:
https://www.python.org/dev/peps/pep-0008/
In particular look at the description for: "double_leading_and_trailing_underscore"

Categories

Resources