I am very new to python so please try keep answers very simple, as I struggle to understand the answers on similar questions. I have the file Employee.py
class Person:
def __init__(self,name,job):
self.name = name
self.job =job
def getEmployeeDescription(self):
return self.name + " is a " + self.job
This is stored on my desktop. I want to import this into cmd so I can do for example
p = Person("James","Builder")
p.name
Python works on cmd, I just dont know exactly what needs to be typed in to allow me to access this class. I tried cd Desktop > python employee.py, but this just runs the file whereas I want to be able to use the class
Open a Python REPL by typing python into the command line
Import the appropriate class that you want to use
Use the class as needed
Here's an example:
$python3
>>> from employee.py import Person
>>> person = Person('name', 'job')
Related
I have written new convenience function(greet.py) in python in order to use it on GDB.
class Greet (gdb.Function):
"""Return string to greet someone.
Takes a name as argument."""
def __init__ (self):
super (Greet, self).__init__ ("greet")
def invoke (self, name):
return "Hello, %s!" % name.string ()
Greet ()
Now I would like to use it on GDB as convenience function. What are the procedures I should do in order to use it while debugging a program on GDB?
As you discovered there's no built in user directory from which scripts are auto-loaded.
Usually a user would source individual scripts from their ~/.gdbinit file, like this:
source /home/user/gdb/scripts/my-script.py
If a user really wants scripts to be auto-sourced from a directory without having to add them to their ~/.gdbinit then this is easily done by adding the following into ~/.gdbinit:
python
import os
directory = '/home/user/gdb/scripts/'
if os.path.isdir (directory):
for filename in sorted (os.listdir(directory)):
if filename.endswith (".py") or filename.endswith (".gdb"):
path = os.path.join(directory, filename)
gdb.execute ("source {}".format (path))
end
This will load all *.py and *.gdb scripts from /home/user/gdb/scripts/.
In order to write new convenience function in GDB :
write the function and place it under "~/gdb/python/lib/gdb/function"
import gdb
class Salam(gdb.Function):
"""Return string to greet someone.
Takes a name as argument."""
def __init__(self):
super(Salam, self).__init__("salam")
def invoke(self, name):
return "Salam, jenap %s!" % name.string ()
Salam()
Edit "~/gdb/data-directory/Makefile.in" and under "PYTHON_FILE_LIST" add "gdb/function/salam.py"
./configure
make
make install
Now, after #gdb
try typing : "print salam("Aman")"
In order the convenience function to work, it must have python support under GDB.
I am getting the NameError anytime i create an instance/object from a class Person
i have created a class saved as Person.py
on the terminal i have imported everything using 'python -i'
i typed P1=Person("name","name",20)
but i got the following error
python -i
Python 2.7.15+ (default, Nov 27 2018, 23:36:35)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> p1=Person("i","j",20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Person' is not defined
Code:
class Person:
#constructor
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
#set first_name
def setFirst_name(self,first_name):
self.first_name = first_name
#get first_name
def getFirst_name(self):
return self.first_name
#set last_name
def setLast_name(self,last_name):
self.last_name = last_name
#get last_name
def getLast_name(self):
return self.last_name
#set age
def setAge(self,age):
self.age = age
#get age
def getAge(self):
return self.age
#get full_name
def getFull_name(self):
return self.first_name + " " + self.last_name
#get details
def getDetails(self):
details = {'First Name':self.first_name,'Last Name':self.last_name,'Age':self.age}
i expected P1 to create an object of Person so that when i call the function 'getDetails()' it should print the follow
First Name:i Last Name: j Age: 20
You have to import a local file before you can use it - even if that file is in the same directory. This should work:
>>> import Person
But now, Person represents the contents of the file Person.py. To actually get to the Person class, you'll need to invoke it explicitly:
>>> p1 = Person.Person("i", "j", 20)
You can get around this by importing the class Person from the file Person.py:
>>> from Persion import Person
>>> p1 = Person("i", "j", 20)
So you're just running a python shell in the working directory where the Person.py file you wrote is located?
This isn't enough to tell the shell/Python that you want to use that file's content. Anything not already defined in that shell instance must be explicitly imported. (with correct capitalisation)
If you're working directly on the shell with -i then you must include arguments to go after that. Those being the file names you want, so your full line will be python -i "Person.py".
If in future however you want to work in a script then this isn't possible and you'll need to specify imports in the "main" file you're working in and require your other files to be called to.
e.g.
#import ModuleName
# in this case your "module" is the "Person.py" file so:
import Person
This will then allow you to use the content of that "module"/file from the shell/script you're working in. To use your Class that is inside that module, which is also named "Person", you'll need to reference to it like Person.Person(args)
Of course that extra writing is going be annoying to look at so we can clean it up by importing specifically that Class as so:
#from Module import Class
from Person import Person
# now we can just use Person(args) without having to specify the Person module every time
For future reference, as I assume you're learning about Classes:
If you have several classes inside a single module/file, say you added an Animal Class, then you can import them one by one, or all of them at once with an asterisk like so:
#either
from Person import Person, Animal
#or
from Person import *
Please don't mark as duplicate, other similar questions did not solve my issue.
This is my setup
/main.py
/actions/ListitAction.py
/actions/ViewAction.py
Main.py:
from actions import ListitAction, ViewAction
ListitAction.py:
class ListitAction(object):
def __init__(self):
#some init behavior
def build_uri():
return "test.uri"
ViewAction.py
from actions import ListitAction
class ViewAction(ListitAction):
def __init__(self, view_id):
ListitAction.__init__(self)
self.view_id = view_id
def build_uri():
return "test"
Running:
$ python3 main.py
The only error message I receive is:
Traceback (most recent call last):
File "/home/jlevac/workspace/project/listit.py", line 11, in <module>
from actions import ListitAction, ViewAction, CommentsAction
File "/home/jlevac/workspace/project/actions/ViewAction.py", line 3, in <module>
class ViewAction(ListitAction):
TypeError: module.__init__() takes at most 2 arguments (3 given)
Even if I try for the python3 console, I received the same error message:
$python3
from actions import ViewAction
I am new to Python, but not new to programming. I'm assuming that my error messages have to do with the import statements, but based on the message I can't really figure out what it means.
Your imports are wrong, so you're trying to inherit from the modules themselves, not the classes (of the same name) defined inside them.
from actions import ListitAction
in ViewAction.py should be:
from actions.ListitAction import ListitAction
and similarly, all other uses should switch to explicit imports of from actions.XXX import XXX (thanks to the repetitive names), e.g. from actions import ListitAction, ViewAction must become two imports:
from actions.ListitAction import ListitAction
from actions.ViewAction import ViewAction
because the classes being imported come from different modules under the actions package.
You are passing self when you don't need to, that's all.
Edit: see MSeifert's comment answer since I don't want to steal content.
If your file is in the root directory of the project then you can directly write the file name and import.
For example, if filename is Parent1.py and class name is Parent, then you would write
from Parent1 import Parent
However, if your file Parent1.py is under any folder for example:
DemoFolder -> Parent1.py- > Parent
(Folder). (File). (Class name)
Then you would have to write:
from Test.Parent1 import Parent
Creating classes and instance of variables
class Student:
# Creating a Class Variables
perc_Raise = 1.05
# Creating a constructor or a special method to initialize values
def __init__(self,firstName,lastName,marks):
self.firstName = firstName
self.lastName = lastName
self.email = firstName + "." + lastName +"#northalley.com"
self.marks = marks
def fullName(self):
return '{} {}'.format(self.firstName,self.lastName)
def apply_raise(self):
self.marks = int(self.marks * self.perc_Raise)
Creating a two instance variable for a Student class
std_1 = Student('Mahesh','Gatta',62)
std_2 = Student('Saran','D',63)
print(std_1.fullName())
print(std_1.marks)
std_1.apply_raise()
print(std_1.marks)
print(std_1.email)
print(std_1.__dict__)
print(std_2.fullName())
print(std_2.marks)
std_2.apply_raise()
print(std_2.marks)
print(std_2.email)
print(std_2.__dict__)
print(Student.__dict__)
Inheritance
class Dumb(Student):
perc_Raise = 1.10
def __init__(self,firstName,lastName,marks,prog_lang):
super().__init__(firstName,lastName,marks)
self.prog_lang = prog_lang
std_1 = Dumb('Suresh','B',51,'Python')
print(std_1.fullName())
print(std_1.marks)
std_1.apply_raise()
print(std_1.marks)
print(std_1.prog_lang)
How do I import a Python file and use the user input later?
For example:
#mainprogram
from folder import startup
name
#startup
name = input('Choose your name')
What I want is to use the startup program to input the name, then be able to use the name later in the main program.
You can access that variable via startup.name later in your code.
name will be in startup.name. You can use dir(startup) to see it.
Or, as an alternate solution:
# Assuming from the names that 'folder' is a folder and 'startup' is a Python script
from folder.startup import *
now you can just use name without the startup. in front of it.
I think is better do your code in classes and functions.
I suggest you to do:
class Startup(object):
#staticmethod
def getName():
name = ""
try:
name = input("Put your name: ")
print('Name took.')
return True
except:
"Can't get name."
return False
>> import startup
>> Startup.getName()
I'm trying to implement a python cmd, using the cmd module. I want to autocomplete files, so I've implemented some methods, however, I've seen that the text parameter from "complete_put(self, text, line, begidx, endidx):" strips all the '/' characters. Anyone knows why, and how can I avoid this behaviour? Thanks :)
I solved it. Just had to modify the set_completer_delims attributes.
This is the code I used, it's based on several examples found on the Internet.
import os
import cmd
import readline
class Shell(cmd.Cmd, object):
def __init__(self):
cmd.Cmd.__init__(self)
def __complete_path(self, path=None):
return ['/bin', '/boot', '/etc']
def do_put(self,args):
print args
def complete_put(self, text, line, begidx, endidx):
print text
if not text:
return self.__complete_path()
return self.__complete_path(text)