I have a niche problem. I create a class classA, with attributes name and number. Once a class item is created, its name is stored as a string in a list, namesList. Later in the code, namesList prints and the user can enter a string input. If that input matches a string in namesList, I want the program to print the number attribute associated with that class item. How should I do this?
ClassA is just a class. You tried to reference it in the last line which leads to an error. Instead of doing that appending the object to the list would be better because then you can individually get the value back from the object while searching in the array.
namesList = []
class classA:
def __init__(self, name, number):
self.name = name
self.number = number
namesList.append(self)
def getNumber(self):
return self.number
def getName(self):
return self.name
example = 'c'
classA(example, 5)
userChoice = input('Which name do you need the number for?')
for name in namesList:
if name.getName() == userChoice:
nameIndex = namesList.index(name)
print(nameIndex)
print('The current price for', name.getNumber())
I think what you're trying to do is this:
namesList = []
class classA:
def __init__(self, name, number):
self.name = name
self.number = number
namesList.append(self.name)
example_Class = classA('example', 5)
userChoice = input('Which name do you need the number for?')
for name in namesList:
if name == userChoice:
print('The number is', example_Class.number)
You have to set classA('example', 5) equal to a variable example_Class and then if you want to access the number value stored it's just example_Class.number
EDIT
This code ought to work regardless of how many class items there are:
class Iterator(type):
def __iter__(cls):
return iter(cls.namesList)
class ClassA(metaclass=Iterator):
namesList = []
def __init__(self, name, number):
self.name = name
self.number = number
self.namesList.append(self)
example_Class1 = ClassA('one', 8)
example_Class2 = ClassA('two', 7)
example_Class3 = ClassA('three', 6)
userChoice = input('Which name do you need the number for?')
for class_name in ClassA:
if class_name.name == userChoice:
print('The number is', class_name.number)
Related
class Satellite:
def __init__(self, message):
print(message)
self.name = input("name: ").title()
self.lbs = int(input("lbs: "))
self.speed = int(input("speed: "))
lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
lstSat.append(Satellite("Info for satellite "+str(i+1)))
i+=1
e= input("Type O to create another satellite: ").lower()
Hello,
How can I make sure that 2 Satellites cannot be the same?
Please don't ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user's input values.
In order to determine repetition, you need to override the eq dunder method.
Try this:
class Satellite:
def __init__(self, name, lbs, speed):
self._name = name
self._lbs = lbs
self._speed = speed
def __eq__(self, other):
if isinstance(other, str):
return self._name == name
if isinstance(other, type(self)):
return self._name == other._name
return False
def __str__(self):
return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'
lstSat = []
PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '
while input(PROMPT) in 'Oo':
name = input('Name: ').title()
if name in lstSat:
print(f'{name} already in use')
else:
lbs = int(input('lbs: '))
speed = int(input('Speed: '))
lstSat.append(Satellite(name, lbs, speed))
for satellite in lstSat:
print(satellite)
I would go for iteration in list and check names with every satellite
...
while e=="o":
satellite = Satellite("Info for satellite " + str(i+1))
if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
lstSat.append(satellite)
else:
# here do some output or error handling
...
...
and the definition of check_reapeated_name() would be something like this:
def check_reapeated_name(lstSat, satellite_name):
for i in lstSat:
if i.name == satellite_name:
return False
return True
I want to print all grades as a csv string for the particular Student. How can i achieve this as it prints out memory location instead:
class Student:
def __init__(self,name,year):
self.name = name
self.year = year
self.grades = []
def add_grade(self,grade):
if type(grade) == Grade:
self.grades.append(grade)
else:
pass
def __repr__(self):
return "Student name is {name} and attends year {year}".format(name=self.name, year=self.year)
pieter = Student("Pieter Bruegel the Elder",8)
class Grade:
minimum_passing = 65
def __init__(self,score):
self.score = score
pieter.add_grade(Grade(100))
pieter.add_grade(Grade(95))
pieter.add_grade(Grade(85))
print(str(pieter.grades)) #this one prints [<__main__.Grade object at 0x7fc3874d76d8>]
print(pieter)
I also added it in the __repr__ but still the same.
Give Grade a __str__ method that returns the score as a string.
class Grade:
minimum_passing = 65
def __init__(self,score):
self.score = score
def __str__(self):
return str(self.score)
Then print(pieter.grades) should print:
[100,95,85]
You can't get rid of the [] surrounding it, because that's the way lists print. You can't customize the container's printing from the elements within it. If you need to do that, you should define your own GradeList class.
I'm new to coding -- taking a Python college course. I know this will be obvious to many of you, but I can not figure out why I continue to get this error attribute error:
prodworker = employee.ProductionWorker(shift_num, pay_rate)
AttributeError: 'Employee' object has no attribute 'ProductionWorker'
Any help is greatly appreciated :)
class Employee: #writing new class called Employee:
def __init__(self, name, number): #accepts arguments for employee name and
self.__name = name #employee number
self.__number = number
def set_name(self, name): #mutator methods to set name and number
self.__name = name
def set_number(self, number):
self.__number = number
#accessor methods returns name and number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
class ProductionWorker(Employee): #write subclass
def __init__(self, shift_num, pay_rate):
Employee.__init__(self, 'ProductionWorker')
self.__shift_num = shift_num
self.__pay_rate = pay_rate
def set_shift_num(self, shift_num):
self.__shift_num = shift_num
def set_pay_rate(self, pay_rate):
self.__pay_rate = pay_rate
def get_shift_num(self):
return self.__shift_num
def get_pay_rate(self):
return self.__pay_rate
#This program creates an instance of Employee Class
#and an instance of Production Worker Class:
again = 'Y'
while again.upper() == 'Y':
print('Enter the following data for the employee: \n')
name = input('What is the employee name?: ')
number = input('What is the employee number? ')
shift_num = input('What is the employee shift number? 1 = Day, 2 = Night :')
while shift_num != '1' and shift_num != '2':
shift_num = input('Invalid entry! Enter 1 for Day shift or 2 for Night shift!')
else:
if shift_num == '1':
shift_num = 'Day'
if shift_num == '2':
shift_num = 'Night'
pay_rate = float(input('What is the employee pay rate? '))
print()
print('This is an instance of the Employee class:')
employee = Employee(name, number)
print('EMPLOYEE: \t\t'+ employee.get_name())
print('EMPLOYEE NUMBER: \t' + employee.get_number())
print()
print('This is an instance of the Production Worker class: ')
prodworker = employee.ProductionWorker(shift_num, pay_rate)
print('SHIFT: \t\t\t' + ProductionWorker.get_shift_num())
print('PAY RATE: \t\t$' + format(ProductionWorker.get_pay_rate(), ',.2f'), sep='')
print('--------------------------------------------')
again = input('Enter Y to add another: ')
if again.upper() != 'Y':
print('Program End')
The ProductionWorker class is a subclass of the Employee class, but that doesn't mean you can call it through an instance of Employee. It's still a top-level class that you should call directly. Try replacing employee.ProductionWorker(...) with just ProductionWorker(...).
You'll get past the current error, but you may have new ones. For instance, I think the current attempt to call Employee.__init__ from ProductionWorker.__init__ will fail because it doesn't pass the right number of arguments. You may also have logic issues, if you expected employee.ProductionWorker to create a ProductionWorker instance that was related in some way to the employee object.
I'd also discourage you from using __double_leading_underscore names for your attributes. That invokes Python's name mangling system, which is mostly intended to help prevent accidental reuse of the same name from different classes in a large or unpredictable inheritance hierarchy. If you just want your attributes to be "private", use a single underscore. That doesn't protect them from being accessed by outside code, but it serves as documentation that they're not part of the object's public API. One of Python's design philosophies is that it's programmers are responsible for their own behavior (often described with the phrase "We're all consenting adults"). If a programmer wants to access an object's private data they can do so (which can be very useful for debugging). But if they break stuff, they have no one to blame but themselves.
I am new to Python, am just learning Classes, and am trying to write a "personal info" program:
This is my code:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
But when I run it it says this:
NameError: global name 'add' is not defined
Can someone please help me?
There are several issues with your code other than the NameError and I strongly suggest you read more on python classes:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes
I'll run you through those issues.
First, the NameError occurs because the add variable was not defined. The same applies to all other arguments you provided in your print statements.
Second, there are issues with the way you define the class methods:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
Here, you are re-assigning the name variable to the return value of raw_input so there's no sense in setting it as an argument in the first place. Also, by stating self.names = name you are re-assigning the class method to the string that is returned by raw_input!
Third, you have to decide whether you want to provide the information when calling the methods, or using raw_input. Here's a working example of your code, assuming you want to use raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()
Here is my code as follows.
# starting of Employee class
class Employee(object):
def __init__(self): #declaring Constructor
self.name = ""
self.iDnumber = ""
self.department = ""
self.jobTitle = ""
# setter methode for setting values to the class properties
def setName(self,name):
self.name=name
def setIDnumber(self,iDnumber):
self.iDnumber=iDnumber
def setDepartment(self,department):
self.department=department
def setJobTitle(self,jobTitle):
self.jobTitle=jobTitle
# getter methode for getting values of the class properties
def getName(self):
return self.name
def getIDnumber(self):
return self.iDnumber
def getDepartment(self):
return self.department
def getJobTitle(self):
return self.jobTitle
# methode which takes object as an argument and display its properties
def display(emp_object):
print("Name : ",emp_object.getName())
print("IDnumber : ",emp_object.getIDnumber())
print("Department : ",emp_object.getDepartment())
print("JobTitle : ",emp_object.getJobTitle())
# Main methode of the program
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
# Initializing each objects of the list
for employee in employeeList:
emp_name = input("Enter your Name ")
employee.setName(emp_name)
emp_iDnumber = input("Enter your iDnumber ")
employee.setIDnumber(emp_iDnumber)
emp_department = input("Enter your Department ")
employee.setDepartment(emp_department)
emp_jobTitle = input("Enter your JobTitle ")
employee.setJobTitle(emp_jobTitle)
# Displaying each objects of the list
for emp_object in employeeList:
display(emp_object)
and, when I run it termianl just flash for a 10th of seconds and do not ask for input.
Help me with this thank you.
I am trying to focus on
Display a message asking user to enter employee name, ID, department, and title
b. Read employee name into a variable
c. Call the set name method of the first object passing the name
d. Read employee ID into a variable
Probably you are running it on windows... Simple add a input() at the end of you main to pause program and prevent windows from close it
And you need to indent your code
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
input()