This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 2 years ago.
What does the last part of this code do exactly? Also why is self.name equal to name? here is the code below:
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
sammy = Shark("Sammy")
sammy.be_awesome()
stevie = Shark("Stevie")
stevie.swim()
if __name__ == "__main__":
main()
Firs part of your question is answered here
Second question
name is the argument passed when creating a instance of your class. However self.name is a instance variable. The value of this is set to name. Read more about python classes here
The last part of the code:
if __name__ == "__main__":
main()
simply means that when this particular script is run as the entry point file, it will execute the main() function. If the contents are imported by another script, it will ignore the if statement.
self.name = name
assigns the input variable name to the instance variable of the class, in this case it is also called name
Related
All Python learning that I have been doing shows that to create a new object, all I should have to do is define a variable and tell it what class it is. Most times when I do this, I get an error. What am I missing?
According to just about everything I've been reading or watching on the subject, the code below should work to create a new Railroad object. I have the class as a separate file, which I then include in the main program. The one time I have gotten this to work perfectly is when I created the object as part of a list instead of a stand-alone.
class Railroad:
def __init__(self):
self.name = "Railroad"
self.repmks = "RRRR"
#include Railroad
def create_rr():
rr = Railroad()
rr.name = input("Railroad name: ")
rr.repmks = input("Reporting marks: ")
When this code runs, I get a traceback error telling me "name 'Railroad' is not defined." Did I not already define it as being a class?
You are missing indent.
This part:
class Railroad:
def __init__(self):
self.name = "Railroad"
self.repmks = "RRRR"
needs to be:
class Railroad:
def __init__(self):
self.name = "Railroad"
self.repmks = "RRRR"
You probably need to return the rr variable inside your function.
Here an example:
script1.py
class Railroad:
def __init__(self):
self.name = "Railroad"
self.repmks = "RRRR"
script2.py
from script1 import Railroad
def create_rr():
rr = Railroad()
rr.name = input("Railroad name: ")
rr.repmks = input("Reporting marks: ")
return rr
test = create_rr()
print(test.name)
Thank you to Daniel, Barmar, and Igor - yes, I had mixed up my C++ dabbling with actual Python syntax and didn't import the files correctly. The indent actually wasn't the issue; it was indented in my program but not in the sample code.
Context:
I developed a python script to be run on a remote linux server. Running using Python 3.6.1. The script worked but was very messy, and procedurally written as opposed to OO. So, I re-wrote this script into 2 different classes. One main class and a blueprint class for objects.
My script is a lot more complicated, i just simplified it for this question.
Desired Function:
Read values from CSV file. Create Objects from these values, 1 object per line. Do some calculations on the values on init'ing the object (in the objects class). Have these objects be accessible from the main class (Base class).
Problems:
I need some clarification on:
The main method is not running. Tried variants on the method call, like Base.main(), including the "if name" statement inside the Base class, and it complains about self not being defined
The "self" reference. Are my usages of this correct? For example: Adding the attribute "age" into the Person objects so you can access it with person.age for example. My method call "self.input_file_handling(Base.inputFilePath)" etc.
Script:
import csv
class Person:
def calculate_age(self):
self.age = 2017 - self.birthYear
def __init__(self, name, birthYear):
self.name = self.strip_characters(self, name)
self.birthYear = int(birthYear)
self.calculate_age()
class Base:
inputFilePath = "input.csv"
people = []
def main():
self.input_file_handling(Base.inputFilePath)
#More methods here
#staticmethod
def input_file_handling(input_file_path):
input_file_path = str(input_file_path)
with open(input_file_path, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
name = line['Name']
age = line['age']
person = Person(name, age)
people.append(person)
if __name__ == '__main__':
main()
First the main method of Base class is not static because it use the self variable, so is necessary receive that.
If you want call the main method and use the self variable you need make something like that:
class Base:
def main(self):
pass
if __name__ == '__main__':
instance_of_base = Base()
instance_of_base.main()
You can call the input_file_handling method without using self, because it's static
Base.input_file_handling(Base.inputFilePath)
I think you need learn more about how python resolve static things and the class and object variables.
Python is not C. There is no main function that automagically executes.
The main method that you defined is inside Base class, but it doesn't accept an argument for the instance.
Either modify it so it accept it (ie self by the convention) or make it a static method.
Then in if __name__ == '__main__': either use Base().main() or Base.main(), depending on what approach you decided to take.
But you don't seem to need any of this, and only doing it for the sake of forcing Python to look/work as other languages (looking at you C++/Java). Python doesn't require you to have a class or a 'main' function/method to execute code.
Your code written in a Pythonic way would be: (Python3)
import csv
from time import time, gmtime
INPUT_FILE_PATH = "input.csv"
class Person:
def __init__(self, name, birth_year):
self.name = name.strip()
self.birth_year = birth_year
#property
def birth_year(self):
return self._birth_year
#setter.birth_year
def birth_year(self, value):
self._birth_year = value
self._age = gmtime(time()).tm_year - value
#property
def age(self):
return self._age
#setter.age
def age(self, value):
self._birth_year = gmtime(time()).tm_year - value
self._age = value
def input_file_handling(input_file_path):
people = []
with open(input_file_path, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
people.append(Person(line['Name'], int(line['age'])))
return people
if __name__ == '__main__':
people = input_file_handling(INPUT_FILE_PATH)
You seem to come from a OOP-only language (C# maybe?).
Some tips:
Avoid globals when able for variables, use them for function definition, class definition and constants.
Do not use a new class to store functions that do not require it
Use lower case and '' for variable and function names, Use CamelCase for class names, use caps and '' for constants.
Use duck typing: do not check that a argument is of a given type, try to use it as if it was and handle throw exceptions if it isn't.
Properties ar your friends if you want to force a specific bahaviour at getting or setting a class attributes
If you do not understand somehting ask in the comments.
This question already has answers here:
class method with no arguments produces TypeError
(3 answers)
Closed 6 years ago.
class Person:
def __init__(self, name):
self.name = name
def printName():
print "my name is %s" % self.name
Mitchell = Person("Mitchell")
Mitchell.printName()
This code throws this error:
Traceback (most recent call last):
File "/home/mitch/Desktop/test.py", line 8, in <module>
Mitchell.printName()
TypeError: printName() takes no arguments (1 given)
I'm sure I did this correctly...
you missed the self param in the printName function definition
class Person:
def __init__(self, name):
self.name = name
def printName(self):
print "my name is %s" % self.name
Because you forgot to add self explicitly to printName instance method. It should have been like
def printName(self):
...
Python implicitly passes object instance to every instance method. Although not directly related to the question, try to use pep8 conventions when you are working with Python. According to pep8 function names are snake-cased not camel-cased and so are variable names. So use print_name and `mitchell' instaed of their camel and pascel-cased counterparts.
This question already has an answer here:
Python: NameError: global name 'foobar' is not defined [duplicate]
(1 answer)
Closed 7 years ago.
I am getting the following Name Error in my python program though I declared the function before it is used.
Here is my program:
def __init__(self):
self.root = None
def insert_at(leaf, value):
#some code here....
def insert(self,value):
#some code here....
insert_at(self.root, value)
def main():
#some code here
insert(10)
#some code here
Here is my error:
File "programs/binary_tree.py", line 38, in insert
insert_at(self.root, value)
NameError: name 'insert_at' is not defined
I did go through the following questions before asking this question, but couldn't understand why I am getting the error.
Make function definition in a python file order independent
and
Python NameError: name is not defined
Looks like those are methods in a class. You need the following changes:
def insert_at(self, leaf, value): # add self
self.insert_at(self.root, value) # add self
I'm at example of 52 of Learning Python the Hard Way wich consist of creating a text based game. Therefore I have two important modules map.py and app.py and one show_room.html on which I'm working on.
map.py contains a room "laser weapon armory" where the user has to guess a 4 digit code.
I'm trying to introduce a cheat code which will reveal the code.This consists of introducing an if clause in app.py.
map.py:
code=("%s%s%s%s"%(randint(0,9),randint(0,9),randint(0,9),randint(0,9)))
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def some_other_functions:
....
laser_weapon_armory = Room("Laser Weapon Armory",description)
app.py (read the important part):
import web
from gothonweb import map
urls = ('/game', 'GameEngine',
'/', 'Index',)
some_code
class GameEngine(object):
def GET(self):
if session.room:
return render.show_room(room=session.room)
def POST(self):
form = web.input(action="")
#Here is the important part:
if session.room == map.laser_weapon_armory:
if form.action == "you tell me":
map.laser_weapon_armory.description+=map.code
elif form.action != map.code:
form.action ='*'
if session.room and session.room.go(form.action):
session.room = session.room.go(form.action)
web.seeother("/game")
That if clause at the important part is never getting verified. Mainly because when 'session.room' becomes equal to 'laser_weapon_armory' it shows up as a diffrent object.
i.e:
print(laser_weapon_armory) ##<gothonweb.map.Room object at 0x01FDE550>
whereas
print(session.room) ##gives <gothonweb.map.Room object at 0x0205E230>
Why does this happens, whereas other imports give the same object?