I want to call a method of class A, from class B; but I get an error which I do ot understand.
Can anyone help me resolve my issue?
Here’s my code and error:
class Environment:
def init(self,state):
self.loc1_ = ‘A’
self.loc2_ = ‘B’
self.state_ = state
def setloc1_state(self,state): #state='D'
self.state_[0] = state
def clean(self):
place = self.getlocation()
if place == 'A':
Environment.setloc1_state(self,'C')
if place == 'B':
Environment.setloc2_state(self,'C')
def main():
init_state = [‘D’,‘D’]
house = Environment(init_state)
vacuum = Agent(percept=house.getstate(),location='A')
while house.getstate() != ['C','C']:
vacuum.execute_action(house.getstate())
print(house.getstate())
main()
I get this error:
AttributeError: ‘Agent’ object has no attribute ‘state_’; related to this line of the clean() function:
“Environment.setloc1_state(self,‘C’)”
I read several tutorials which explains this concept ofcalling class members from another class, and those examples worked. So, I’m not sure why this code snippet does not distinguish between the “self” variabble linked to the 2 different classes.
I don’t know what Digi product you are working with, but the product may not support the class function or it could be that the version of Python supported by the device uses a different call for Class.
Replace:
def clean(self):
place = self.getlocation()
if place == ‘A’:
Environment.setloc1_state(self,‘C’)
if place == ‘B’:
Environment.setloc2_state(self,‘C’)
with:
def clean(self):
place = self.getlocation()
if place == ‘A’:
self.percept_.setloc1_state(self,‘C’)
if place == ‘B’:
self.percept_.setloc2_state(self,‘C’)
Well, there are some issues with your code.
Can you try below code, hope it can fix your error.
class Environment:
def __init__(self, state):
self.loc1_ = 'A'
self.loc2_ = 'B'
self.state_ = state
def setloc1_state(self, state):
self.state_[0] = state
class Agent:
def __init__(self, percept, location='A', action='N', goal=['C', 'C']):
self.percept_ = percept
self.cost_ = 0
self.location_ = location
self.action_ = action
self.goal_ = goal
def clean(self):
place = self.location_
if place == 'A':
# You need to access the Environment object to call setloc1_state
self.percept_.setloc1_state('C')
if place == 'B':
# You may want to add a setloc2_state method in Environment as well
self.percept_.setloc2_state('C')
def main():
init_state = ['D', 'D']
house = Environment(init_state)
vacuum = Agent(house, location='A') # Pass the Environment instance to Agent
while house.state_ != ['C', 'C']:
vacuum.clean()
print(house.state_)
if __name__ == "__main__":
main()