I am new to learning Python and currently I am working on Classes. Below is a program that I am referring to. However, on calling the class, I am getting the following error:
from airtravel import *
a = Aircraft("G-EUPT", "Airbus A319", num_rows=22, num_seats_per_row=6)
Error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Aircraft' is not defined
Code:
class Flight:
def __init__(self, number):
if not number[:2].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:2].isupper():
raise ValueError("Invalid route number '{}'".format(number))
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError("Invalid route number '{}'".format(number))
self._number = number
def number(self):
return self._number
def airline(self):
return self._number[:2]
class Aircraft:
def __init__(self, registration, model, num_rows, num_seats_per_row):
self._registration = registration
self._model = model
self._num_rows = num_rows
self._num_seats_per_row = num_seats_per_row
def registration(self):
return self._registration
def model(self):
return self._model
def seating_plan(self):
return(range(1, self._num_rows + 1),
"ABCDEFGHJK"[:self._num_seats_per_row])
Where am I going wrong? Kindly help me understand. Why am I receiving this error?
I plan to execute the command a.Registration to get G-EUPT as the output.
this is a basic question in python for the new ,the python searchs for file path,
I guess the airtravel is that you create .PY(airtravel.py) file in your folder
like this:
and you will get the answer:
and if you learn more about import python file ,you can look here.
the import in python
from airtravel import (Aircraft, Flight)
Related
I am building a python code to validate the email address and the phone number in a given CSV file using pandas and I want to write a separate CSV file with only the validated values. I am totally new to python and I have written a code for the functionality as follows:
from email_validator import validate_email, EmailNotValidError
import pandas as pd
import re
file = r'sample.csv'
filtered = r'filtered.csv'
valid = r'Valid.csv'
df=pd.read_csv(file)
def eVali(dataFrame):
try:
validate_email(dataFrame)
return True
except EmailNotValidError:
return False
def phoneValid(dataFrame):
if re.search("\w{3}-\w{3}-\w{4}",dataFrame):
return True
else:
return False
df["Email_validate"] = df['email'].apply(eVali)
df_fltrd = df[df['Email_validate']]
#del df_fltrd['Email_validate']
print(df_fltrd)
df_fltrd["Phone_validate"] =df_fltrd['phone'].apply(phoneValid)
df_valid = df_fltrd[df_fltrd["Phone_validate"]]
del df_valid["Phone_validate", "Email_validate"]
print(df_valid)
df_fltrd.to_csv(filtered)
df_valid.to_csv(valid)
This code is working fine and I could create a new CSV with validated values as I require. but when I tried to organize this code as a proper class with the proper method it gives an error saying,
Traceback (most recent call last):
File "E:\myTasks\validator.py", line 7, in <module>
class Validator:
File "E:\myTasks\validator.py", line 47, in Validator
validation(self.file)
AttributeError: module 'self' has no attribute 'file'
This is the class I created.
Validator.py
import self as self
from email_validator import validate_email, EmailNotValidError
import pandas as pd
import re
class Validator:
def __init__(self):
self.file = r'sample.csv'
self.outFile =r'filteredSample.csv'
def emailValid(dataframe):
try:
validate_email(dataframe)
return True
except EmailNotValidError:
return False
def phoneValid(dataframe):
if re.search("\w{3}-\w{3}-\w{4}", dataframe):
return True
else:
return False
def validation(self):
df = pd.read_csv(self.file)
df = df.copy();
df["Email_validate"] = df['email'].apply(Validator.emailValid)
df_filtered = df[df['Email_validate']]
print(df_filtered)
df_filtered["Phone_validate"] = df_filtered['phone'].apply(Validator.phoneValid)
df_valid = df_filtered[df_filtered["Phone_validate"]]
del df_valid["Email_validate"]
del df_valid["Phone_validate"]
print(df_valid)
df_valid.to_csv(self.outFile)
validation(self)
Can someone please help me with this. It will be really appreciated. Thanks in advance!
Well, you can't call an instance method from the class itself
validation(self)
This bit should be outside of your class, for example it could be called from your main function after having instantiated your Validator object.
my_validator = Validator()
my_validator.validation()
You do not import self.
self is the instance you are in at the time of code execution.
Your problem is that you did not understand classes yet. You tried to call a class method within the class which python does but toes not like.
I'd suggest you have a look at https://docs.python.org/3/tutorial/classes.html and/or https://www.w3schools.com/python/python_classes.asp.
You want to push the last line to the end and add
def main():
i = Validator()
i.validation()
if __name__ == "__main__":
main()
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.
I'm trying but it's not working. I have the following code line:
class Run:
def Method(self, choice):
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.start().LoadJson['zip'])
And this is variable, and is within another class, and another function:
class Host_Method:
def start(self):
My_API = requests.get("http://ip-api.com/json/%s" % socket.gethostbyname(sys.argv[2]))
LoadJson = json.loads(My_API.content)
The error:
Traceback (most recent call last):
File "InfoIP.py", line 78, in <module>
elif sys.argv[1] == "-h": Run().Method(Host_Method())
File "/Pentest/InfoIP2/Libraries/InfoIP_Functions.py", line 159, in Method
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.LoadJson['zip'])
AttributeError: Host_Method instance has no attribute 'LoadJson'
You probably want them to be stored in an instance variable (self....). And you probably want your start to be an __init__ method. Your corrected class could look like:
class HostMethod:
def start(self):
self.my_API = requests.get("http://ip-api.com/json/{0}".format(socket.gethostbyname(sys.argv[2])))
self.load_json = json.loads(self.my_API.content)
Then, you could do:
class Run:
def Method(self, choice):
print "{0}Zip :\t{1}{2}\n".decode('utf-8').format(Basic_Green, White, choice.load_json['zip'])
a = Run()
a.method(HostMethod())
See also:
https://docs.python.org/3.4/tutorial/classes.html
In Python, can a constructor take in a method of another class as an argument?
I've heard that you can do something like this, but this example isn't working (currently, I'm getting a 'module' object is not callable error):
class GeneticAlgorithm ():
def __init__(self, population, fitness, breed, retain = .3, weak_retain = .15 ) :
self.fitness = fitness
Here fitness is a function defined elsewhere and note that I am importing the class where the function is defined.
edit: Here's the code that actually produces the error
class Solver( ):
def __init__( self, fitness, breed, iterations ):
self.T = Problem()
self.fitness = fitness
self.breed = breed
self.iterations = iterations
def solve( self ):
P = self.T.population(500)
GA = GeneticAlgorithm(P, self.fitness, self.breed) # problem here
Traceback (most recent call last):
File "C:\Users\danisg\Desktop\Other\Problem.py", line 128, in <module>
main()
File "C:\Users\danisg\Desktop\Other\Problem.py", line 124, in main
t = S.solve()
File "C:\Users\danisg\Desktop\Other\Problem.py", line 74, in solve
GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable
And where the Solver is created
def main():
S = Solver(fitness, breed, 35)
print(S.solve())
if __name__ == '__main__':
main()
From the comments, the root of the issue:
I do `import GeneticAlgorithm'. I should not do this? – gjdanis
No, that's not actually correct. What you've done is import the module, not the class that's inside the module. You have two options here - do one or the other:
Change the import to
from GeneticAlgorithm import GeneticAlgorithm
Change the Solver class to use
GA = GeneticAlgorithm.GeneticAlgorithm(P, self.fitness, self.breed)
I'd suggest renaming the module from GeneticAlgorithm.py to something that isn't quite as confusing (genetic_algorithm.py is a good candidate), then using the first option to import just the class from that module - from genetic_algorithm import GeneticAlgorithm
Yes, you could have something like this:
def eats_a_method(the_method):
pass
def another_method():
pass
eats_a_method(another_method)
Take a look at the stack trace:
GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable
It says GeneticAlgorithm is a module, not a function.
I am new in Python and I wrote the following code:
class Frazione:
def __init__(self, Numeratore, Denominatore=1):
mcd=MCD(Numeratore,Denominatore)
self.Numeratore=Numeratore/mcd
self.Denominatore=Denominatore/mcd
def MCD(m,n):
if m%n==0:
return n
else:
return MCD(n,m%n)
def __str__(self):
return "%d/%d" %(self.Numeratore, self.Denominatore)
def __mul__(self, AltraFrazione):
if type(AltraFrazione)==type(5):
AltraFrazione=Frazione(AltraFrazione)
return Frazione(self.Numeratore*AltraFrazione.Numeratore, self.Denominatore*AltraFrazione.Denominatore)
__rmul__=__mul__
Open shell at the same folder of Frazione.py:
>>> from Frazione import Frazione
end then
>>> f=Frazione(10,5)
When I press Enter, I receive this output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\Frazione.py", line 5, in __init__
mcd=MCD(Numeratore,Denominatore)
NameError: global name 'MCD' is not defined
PS. I apologize for my english!
MCD is a method of Frazione, but you're calling it as if it were a global function. The easiest (and cleanest, IMHO) fix is to just move it outside the class, because it doesn't need to access any class or instance members.
So:
def MCD(m, n):
if m % n == 0:
return n
else:
return MCD(n, m % n)
class Frazione:
# as before but without MCD
If you do want to keep it in the class, then you might rewrite it to be iterative instead of recursive and call it as self.MCD in __init__. That's a good idea anyway, as Python's support for recursion is rather weak.