Getting an attribute error in Python - python

I know that there are a few post on Python attribute errors but I cannot find anything to help solve my issue or how to fix it. Here is my code:
class Employee:
def __init__(self, name, ID_number, dept, job_title):
self.__name = name
self.__ID_number = ID_number
self.__dept = dept
self.__job_title_number = job_title
#set methods
def set_name(self,name):
self.__name = name
def set_ID_number(self,ID_number):
self.__ID_number = ID_number
def set_dept(self,dept):
self.__dept = dept
def set_job_title(self,job_title):
self.__job_title = job_title
#get methods
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID_number
def get_dept(self):
return self.__dept
def get_job_title(self):
return self.__job_title
def main():
emp1 = Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
print("Information for employee 1:")
print("Name:",emp1.get_name())
print("ID:",emp1.get_ID_number())
print("Department:",emp1.get_dept())
print("Job Title:",emp1.get_job_title())
main()
The traceback that I get is: Traceback (most recent call last):
File "C:/Users....", line 48, in
main()
File "C:/Users....", line 41, in main
print("Job Title:",emp1.get_job_title())
File "C:/Users....", line 29, in get_job_title
return self.__job_title
AttributeError: 'Employee' object has no attribute '_Employee__job_title'

In __init__, you use self.__job_title_number = job_title, but then in get_job_title you use self.__job_title, which at this point hasn't been set.
You need to make your variable name consistent across all uses.

You have not declared the member in the constructor
Must change
self.__job_title_number = job_title
to
self.__job_title = job_title

In your init function inside your class you have job title as self.__job_title_number but in the getter function you return self.__job_title. You have to change one of these so they are the same.

Related

Getting NameError for class variable while accessing it in methods of another class

Actually I wanted to create one instance of Class 'car' and wanted to use that Object within methods of a different class. As 'carObj' is a Class variable of class 'fourWheeler', we can define just before all methods and we can use. This is the understanding I got after going through few tutorials. But why here I am getting this error. I just wanted to understand. Any suggestions/advice will help me a lot.
class car:
def __init__(self,name, mileage):
self.__name = name
self.__mileage = mileage
def SpeedDetails(self):
print("Top Speed : 140")
print("Avg speed : 80")
class fourWheeler:
carObj = car('Honda', 20)
def Vehicletype():
print(carObj)
def VehicleSpeed():
carObj.SpeedDetails()
if __name__ == '__main__':
vehicle = fourWheeler
vehicle.Vehicletype()
vehicle.VehicleSpeed()
The error I got after running the script:
ssh://root#kick-bgl-caas6.cisco.com:41114/kick/bin/python -u /tmp/pycharm_project_977/Test.py
Traceback (most recent call last):
File "/tmp/pycharm_project_977/Test.py", line 20, in <module>
vehicle.Vehicletype()
File "/tmp/pycharm_project_977/Test.py", line 13, in Vehicletype
print(carObj)
**NameError: name 'carObj' is not defined**
Added your mistakes as comments
class car:
def __init__(self,name, mileage):
self.__name = name
self.__mileage = mileage
def SpeedDetails(self):
print("Top Speed : 140")
print("Avg speed : 80")
class fourWheeler:
carObj = car('Honda', 20)
def Vehicletype(self): #missed self here
print(self.carObj)
def VehicleSpeed(self): #missed self here
self.carObj.SpeedDetails()
if __name__ == '__main__':
vehicle = fourWheeler() # use constructor
vehicle.Vehicletype()
vehicle.VehicleSpeed()

How to correctly use shelves when working with classes in Python?

I'm making some code to learn how to use classes better. I learnt about persistence in programs and about shelves in Python.
I'm trying to make my user input some stuff, which then is used to make an object of my only class.
import shelve
filearch = shelve.open('archive')
filearch['patients'] = {}
class Patient():
def __init__(self, name='', surname='', notes=''):
self.name = name
self.surname = surname
self.notes = notes
def makeone():
print('Insert a name')
nome = input('Nome: ')
print('Insert a surname')
cognome = input('surname: ')
print('Insert notes')
data = input('notes: ')
a = {'name': name, 'surname': surname, 'notes': notes}
return a
def addone():
users_pat = Patient(**makeone())
return users_pat
def save(user_paz):
return filearch['patients'].update({user_paz : a)
Can someone please explain me what am i doing wrong?
There are a few things to fix in this code.
Firstly, it doesn't run because this line is invalid, it's missing a closing '}'.
return filearch['patients'].update({user_paz : a)
Once that is fixed, running the code like this
user = addone()
save(user)
results in this error:
Traceback (most recent call last):
File "test.py", line 30, in <module>
user = addone()
File "test.py", line 21, in addone
users_pat = Patient(**makeone())
File "test.py", line 18, in makeone
a = {'name': name, 'surname': surname, 'notes': notes}
NameError: name 'name' is not defined
This is because in makeone you assign the input values to nome, cognome and data but try to save the non-existent variables name, surname and notes.
If we fix these names and run again we get:
Traceback (most recent call last):
File "test.py", line 31, in <module>
save(user)
File "test", line 26, in save
return filearch['patients'].update({user_paz: a})
NameError: name 'a' is not defined
In a is the name of a variable that you create in makeone, but that name is only valid inside the makeone function. the save function only knows about the user_paz variable that you have passed to it, so change
return filearch['patients'].update({user_paz : a})
to
return filearch['patients'].update({user_paz : user_paz})
Finally, as mentioned in the comments, you need to close the shelve file to be sure the content are saved.
Here's an improved version of your code: it saves the input and then reports on the contents of the shelve file.
import shelve
class Patient:
def __init__(self, name='', surname='', notes=''):
self.name = name
self.surname = surname
self.notes = notes
def __repr__(self):
# A readable representation of a Patient object.
return '<Patient(name={0.name}, surname={0.surname}, notes={0.notes}>'.format(self)
# Use the same readable representation if str(patient) is called.
__str__ = __repr__
def makeone():
print('Insert a name')
name = input('Nome: ')
print('Insert a surname')
surname = input('surname: ')
print('Insert notes')
notes = input('notes: ')
a = {'name': name, 'surname': surname, 'notes': notes}
return a
def addone():
users_pat = Patient(**makeone())
return users_pat
def save(user_paz):
with shelve.open('archive') as archive:
archive['patients'] = {user_paz.name: user_paz}
return
def report():
with shelve.open('archive') as archive:
for name, patient in archive.items():
print(name, patient)
return
def main():
patient = addone()
save(patient)
report()
return

Not able to access object member variables

I am new to python and am facing a strange error.
The basic idea of my demo is to perform "Constructor Overloading" in python, similar to other programming languages.
I have two files, one file that holds only the class, and another file to create objects of the class.
employee.py
class Employee:
def displayEmployee(self):
print("Name : ", self.emp_name, ", Salary: ", self.salary)
def __init__(self,id=None,salary=None,emp_name=None):
print("Constructing MyClass")
if(id is None):
self.id=101
else:
self.id = id
if(salary is None):
self.salary=20000
else:
self.salary = salary
if(emp_name is None):
self.emp_name="Default"
else:
self.emp_name = emp_name
runner.py
from employee import Employee
emp1 = Employee()
emp2 = Employee(1,3000,"Abcd")
emp1.displayEmployee();
emp2.displayEmployee();
However, now I am facing an error as
Traceback (most recent call last):
File "runner.py", line 7, in <module>
emp2.displayEmployee();
File "D:\python\Demo\employee.py", line 3, in displayEmployee
print("Name : ", self.emp_name, ", Salary: ", self.salary)
AttributeError: 'Employee' object has no attribute 'emp_name'
That means I am not able to access any of the member variables of the class in a function of the same class. This is quite puzzling to me with respect to other programming languages.
Am I doing something wrong or is this by design?
UPDATE:
Based on the recommendation I have updated the python files to the following. However, I am still facing the same error, which is also given below.
employee.py
class Employee:
def displayEmployee(self):
print("Name : ", self.emp_name, ", Salary: ", self.salary)
def __init__(self, id=101, salary=20000, emp_name="Default"):
print("Constructing MyClass")
self.id = id
self.salary = salary
self.emp_name = emp_name
runner.py
from employee import Employee
emp1 = Employee()
emp1.displayEmployee();
Error:
Traceback (most recent call last):
File "runner.py", line 6, in <module>
emp1.displayEmployee();
File "D:\python\Demo\employee.py", line 3, in displayEmployee
print("Name : ", self.emp_name, ", Salary: ", self.salary)
AttributeError: 'Employee' object has no attribute 'emp_name'
If you pass arguments that are not None they are never assigned as attributes of self. You could modify your __init__ to simply provide default values then assign them as attributes to your class
def __init__(self, id=101, salary=20000, emp_name="Default"):
print("Constructing MyClass")
self.id = id
self.salary = salary
self.emp_name = emp_name

TypeError: 'str' object is not callable Python 3.6.1

I create python Project and make a class with some methods and property (variable) when I run my script the Python Interpretation tell me:
Traceback (most recent call last):
child.class#gmail.com
File "C:/.../Python_Tutorials/Object_Orinted_Programming.py", line 272, in
Child_Instance.name("child")
TypeError: 'str' object is not callable
it is the Code:
class Mother_Class:
def __init__(self,parm1,parm2):
self.name = (parm1)
self.family = (parm2)
self.full_name = (self.name + " " + self.family)
self.email = (self.name+"."+self.family+"#gmail.com")
def full_name(self,parm1,parm2):
print ("Your Full Name is: "+parm1 + "" + parm2)
class Child_Class(Mother_Class):
def name(self,name):
name = ( name )
def family(self,family):
family = ( family )
def Some_Methods(self):
print ("Some information is Here: ")
Instance = Mother_Class("mother","class")
print (Instance.full_name)
print (Instance.email)
print ("")
Child_Instance = Child_Class("child","class")
Child_Instance.name("overwriteclass")
print (Child_Instance.full_name)
What are the Problems?
The following method rewrites the method name with the value passed to the function.
def name(self,name):
name = ( name )
So, when you then try to call the "method", you're actually trying to call the string that you overwrote the method with.
Fixing is going to require a structural change of some sort because you are trying to use name as both a method name and a property name. Maybe:
def set_name(self, name):
self.name = name

TypeError: 'tuple' object is not callable when trying to call method

Here is what I have going on so far:
# -*- coding: cp1252 -*-
import time
class Item():
def __init__(self, name, description, base_value):
self.name = name
self.description = description
self.ingredients = ingredients
self.base_value = value
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value)
class Metal(Item):
def __init__(self, name, description, ingredients, base_value):
self.smelt_time = smelt_time
self.smelted = smelted
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value, self.smelt_time, self.smelted)
class Bronze_Ingot(Metal):
def __init__(self):
self.name = "Bronze Ingot",
self.description = "A refined ingot of bronze."
#self.ingredients = Tin_Ore(1)+Copper_Ore(1) <--- I will get these lines working later...
self.base_value = 33
self.smelt_time = 15
self.smelted = ()
class Fuel(Item):
def __init__(self, name, description, ingredients, base_value):
self.fuel_time = fuel_time
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value, self.fuel_time)
class Cloth(Fuel):
def __init__(self):
self.name = "Cloth",
self.description = "A piece of cotton cloth."
#self.ingredients = 2 Cotton <--- I will get these lines working later...
self.base_value = 2
self.fuel_time = 5
But I am having great trouble with this function...
def smelted(Fuel, Metal):
if (Fuel.fuel_time - Metal.smelt_time) > 0:
time.sleep(1)
print "Smelting", Metal.name, "..."
time.sleep(Metal.smelt_time)
print "Time to forge!"
The problem is more or less making it work. My friend and I have tried EVERYTHING that we can think of when running this function, but to no avail. Here is our most recent attempt:
from Smelting_Progress import *
x = Cloth()
y = Bronze_Ingot()
y.smelted(x,y)
After trying to run this, I received this error:
Traceback (most recent call last):
File "C:\Users\WCS-HSSTUDENT\Desktop\Files\Project SAOffline\Coding\New Aincrad World\Items\NAI_Smelted.pyw", line 6, in <module>
Metal.smelted(Fuel, Metal)
TypeError: 'tuple' object is not callable
You have an instance attribute smelted; you set it in Metal.__init__():
self.smelted = smelted
Your Bronze_Ingot subclass sets it to an empty tuple:
self.smelted = ()
You cannot have both a method and and a tuple use the same name. Rename one or the other.
If you meant to use your smelted() code as a function, then define it at the top level (same indentation as your classes), and call it as a function, not a method:
smelted(x, y)
(note, no y. in front).

Categories

Resources