Can't get python class initialized correctly [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I'm not sure why this isn't working. The error says my Artist object has no attribute called name. This doesn't make sense to me because I'm looking right at the attribute called name....
Define the Artist class with a constructor to initialize an artist's
information and a print_info() method. The constructor should by
default initialize the artist's name to "None" and the years of birth
and death to 0. print_info() should display Artist Name, born XXXX if
the year of death is -1 or Artist Name (XXXX-YYYY) otherwise.
Define the Artwork class with a constructor to initialize an artwork's
information and a print_info() method. The constructor should by
default initialize the title to "None", the year created to 0, and the
artist to use the Artist default constructor parameter values.
Ex: If the input is:
Pablo Picasso
1881
1973
Three Musicians
1921
the output is:
Artist: Pablo Picasso (1881-1973)
Title: Three Musicians, 1921
If the input is:
Brice Marden
1938
-1
Distant Muses
2000
the output is:
Artist: Brice Marden, born 1938
Title: Distant Muses, 2000
My code:
class Artist:
def __init__(self, name= "None", birth_year = 0, death_year = 0):
name = self.name
birth_year = self.birth_year
death_year = self.death_year
# TODO: Define constructor with parameters to initialize instance attributes
# (name, birth_year, death_year)
def print_info(self):
if self.death_year == -1:
print("{}, born {}".format(self.name,self.birth_year))
else:
print("{} ({}-{})".format(self.name,self,birth_year,self.death_year))
# TODO: Define print_info() method. If death_year is -1, only print birth_year
class Artwork:
def __init__(self,title ="None",year_created = 0, artist=Artist().name):
title = self.title
year_created = self.year_created
artist = self.artist
# TODO: Define constructor with parameters to initialize instance attributes
# (title, year_created, artist)
def print_info(self):
print("Artist: {}, born {}".format(self.artist,Artist().birth_year))
print("Title: {}, {}".format(self.title,self.year_created))
# TODO: Define print_info() method
if __name__ == "__main__":
user_artist_name = input()
user_birth_year = int(input())
user_death_year = int(input())
user_title = input()
user_year_created = int(input())
user_artist = Artist(user_artist_name, user_birth_year, user_death_year)
new_artwork = Artwork(user_title, user_year_created, user_artist)
new_artwork.print_info()
Enter program input (optional)
Pablo Picasso
1881
1973
Three Musicians
1921
Program errors displayed here
Traceback (most recent call last):
File "main.py", line 16, in <module>
class Artwork:
File "main.py", line 17, in Artwork
def __init__(self,title ="None",year_created = 0, artist=Artist().name):
File "main.py", line 3, in __init__
name = self.name
AttributeError: 'Artist' object has no attribute 'name'

You have the class rules backwords in Artist.init()
Classes work so that:
Class MyClass:
def __init__(name,date):
self.name = name
self.date = date
self.name is the class name that gets assigned the name when initialized so doing the opposite should return None or nothing if I'm correct. Just switch those 2 and then doing:
newClass = MyClass("Pablo","2019")
print(MyClass.name)
print(MyClass.date)
returns:
Pablo
2019
If date is date:str on the init() function then str() the date first.

Related

Why am I getting a TypeError when I seem to be filling the paremeters? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to create an object and I'm initializing it with 2 fields first (name & number). However each time I run the program I'm given this error:
TypeError: __init__() missing 1 required positional argument: 'number'
The __init__ method in the class looks like this:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
The code where I try to create the object is this:
employee1 = ProductionWorker(Employee)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1.__init__(name, number)
Does anyone know why I may be getting this error?
Do:
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = ProductionWorker(name, number)
You do not generally need to call __init__ explicitly; it's invoked by the ProductionWorker(...) expression, which passes its arguments to self.__init__ as part of initialization.
You do not need to restate when constructing a new object that Employee is the parent class; that only needs to be said when the class is defined.
You are using the class as a parameter.
Then, init is always automatically called on creation. This how it might work as You want (using the show method to validate):
class Employee:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
def show(self):
print(self.__name__)
print(self.__number__)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = Employee(name,number)
employee1.show()

Python Output Gives Object Address Instead of Values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm having a bit of trouble with this assignment, here's my current code.
This is the Class for the employees on a separate python file.
class Employee:
#Initializes the classes for the employee information
def __init__(self, name, id_number, department, title):
self.set_name = name
self.set_id_number = id_number
self.set_department = department
self.set_title = title
#Sets attributes to the information
def set_name(self, name):
self.name = name
def set_id_number(self, id_number):
self.id_number = id_number
def set_department(self, department):
self.department = department
def set_title(self, title):
self.title = title
#Returns the information's attributes
def get_name(self):
return self.name
def get_id_number(self):
return self.id_number
def get_department(self):
return self.department
def get_title(self):
return self.title
def __str__(self):
return 'Name:' + self.name + \
'\nID Number:' + self.id_number + \
'\nDepartment:' + self.department + \
'\nJob Title:' + self.title
Here is the main code that is supposed to print the information about the employees:
import employee
def main():
#Creates the three instances of the employees
emp1=employee.Employee("Susan Meyers", "47899", "Accounting", \
"Vice President")
emp2=employee.Employee("Mark Jones", "39119", "IT", "Programmer")
emp3=employee.Employee("Joy Rogers", "81774", "Manufacturing", \
"Engineer")
#Prints information about the employees
print("EMPLOYEE INFORMATION:")
print("---------------------")
print("Employee 1:")
print(emp1, '\n')
print("Employee 2:")
print(emp2, '\n')
print("Employee 3:")
print(emp3, '\n')
main()
This is the output I get when I run the 2nd file on this post:
EMPLOYEE INFORMATION:
---------------------
Employee 1:
<employee.Employee object at 0x000002BE14A959D0>
Employee 2:
<employee.Employee object at 0x000002BE14ABB0A0>
Employee 3:
<employee.Employee object at 0x000002BE14B622B0>
Not sure why this is happening, but if anyone could help, it would be much appreciated.
The string conversion function is __str__, not _str_. Adding a _ before and after should fix your problem.
More feedback, while not related to the question:
Use the following to call your main() instead. While not absolutely necessary, it is good practice. It prevents main() from being run if you use the .py file in an import statement.
if __name__ == "__main__":
main()
In the constructor of your class, the usage of the setter functions is incorrect. You need to call them instead of setting them.
Afterwards, it should work:
https://ideone.com/2mnd3g

Continuous error in module: TypeError: Artist() takes no arguments

Working through an assignment, and have tried multiple changes to both the Class and the Module but I still am getting an error, "TypeError: Artist() takes no arguments".
The assignment states:
Define the Artist class in Artist.py with a constructor to initialize an artist's information. The constructor should by default initialize the artist's name to "None" and the years of birth and death to 0.
Define the Artwork class in Artwork.py with a constructor to initialize an artwork's information. The constructor should by default initialize the title to "None", the year created to 0, and the artist to use the Artist default constructor parameter values. Add an import statement to import the Artist class.
Add import statements to main.py to import the Artist and Artwork classes.
Ex:
If the input is:
Pablo Picasso
1881
1973
Three Musicians
1921
the output is:
Artist: Pablo Picasso (1881-1973)
Title: Three Musicians, 1921
If the input is:
Brice Marden
1938
Distant Muses
2000
the output is:
Artist: Brice Marden, born 1938
Title: Distant Muses, 2000
My Code:
class Artist:
def __init__(self, name ="None", birth_year = 0, death_year = 0):
"""
Constructor to initialize the name, birth_year and death_year to specified values
default of "None", 0 and 0 respectively
"""
self.name = name
self.birth_year = birth_year
self.death_year = death_year
def print_info(self):
"""
Function to display the information of the Artist
"""
if self.death_year == -1:
print('Artist: {}, born {}'.format(self.name, self.birth_year))
else:
print('Artist: {} ({}-{})'.format(self.name, self.birth_year, self.death_year))
#end of Artist.py
from Artist import Artist
class Artwork:
def __init__(self, title = "None", year_created = 0, user_artist = Artist()):
"""
Constructor to initialize the title, year_created and artist to specified values
default of "None", 0 and default artist respectively
"""
self.title = title
self.year_created = year_created
self.artist = user_artist
def print_info(self):
"""
Function to display the information of the Artwork
"""
self.artist.print_info() # display the information for Artist
print("Title: %s, %d" % (self.title, self.year_created))
#end of Artwork.py
from Artist import Artist
from Artwork import Artwork
if __name__ == "__main__":
user_artist_name = input()
user_birth_year = int(input())
user_death_year = int(input())
user_title = input()
user_year_created = int(input())
user_artist = Artist(user_artist_name, user_birth_year, user_death_year)
new_artwork = Artwork(user_title, user_year_created, user_artist)
new_artwork.print_info()
#end of main.py
ERROR:
Traceback (most recent call last):
File "main.py", line 54, in <module>
user_artist = Artist(user_artist_name, user_birth_year, user_death_year)
TypeError: Artist() takes no arguments
Works fine for me, please make sure you code has proper indentation, it might be an indentation problem.
All of these need to be handled in their respective files inside the embedded interpreter. Makes sure to click the drop down menu and select and fill in the 3 files, main.py, artist.py and artwork.py.
I am dumb.
The code works, if you put it in the right places.

Python returning from class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class Customer: #at this part ı defined the class for the customers in the file
def __init__(self, Name, Surname, Age, Balance):
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
def __str__(self):
return("Hello, "+str(self.name)+" "+str(self.sname)+" You have "+ str(self.balance)+" dollars in your account.");
Hello, you can see my class above
My aim - ask users name/surname and get the str part in the class.
I'm getting informations about customers from csv file.
ans = input("name")
ans2 = input("surname")
a = Customer(ans,ans2)
print(a)
With this part I've tried to do part that I explained above but I could'nt make the code work.
You have to define all the other attributes the class instance supposed to have that is Name, Surname, Age, Balance where you have only given Name and Surname. Python will also expect all other attributes you have given in __init__
Take this for example:
Age = input("age") #add these to take input too
Balance = input("balance") #add these to take input too
a = Customer(ans,ans2, Age, Balance)
Well, if your values sometimes supposed to be empty, make some values not necessary as in example:
class Customer:
def __init__(self, Name, Surname, Age=None, Balance=None): # specify the values which would be left as blank
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
# another code here
Then, if you pass only part of data to class constructor, you'll still get a working class instance without any errors:
>>> a = Customer('Name', 'Surname')
>>> a.Name
'Name'
>>> a.Surname
'Surname'
>>> a.Age
>>> # we got None here
Of course, you can use keyboard input too to enter the values, which is not provided by your csv data file by using the input() function.

Total newbie... Need help understanding python classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My understanding of python is zero to none... Been exhausting myself reading what seems like a hundred different ways to approach this. Below I put the assignment description and my code... As of now I am having trouble using the 'getAnimal()' command. I'm not sure what it does or how it works. Thanks in advance :D
Assignment description: "Write a class definition for a class 'Zoo.' It should have instance variables for animal type, herbivore/carnivore/omnivore, and inside/outside. It should also have a getAnimal() method to show the animals information. Write a separate "ZooDriver" class to a) create three instances of zoo animals, b) get user input on which animal to view (1,2,3)c) show the animal info suing getAnimal()."
~~~~~~~~ My code:
class Zoo:
def __init__(self, animal, animal_type, habitat):
self.animal = animal
self.animal_type = animal_type
self.habitat = habitat
user_input=raw_input("Enter the number 1, 2, or 3 for information on an animal.")
if user_input == "1":
my_animal = Zoo("Giraffe", "herbivore", "outside")
elif user_input == "2":
my_animal = Zoo("Lion", "carnivore", "inside")
elif user_input == "3":
my_animal = Zoo("Bear", "omnivore", "inside")
print "Your animal is a %s, it is a %s, and has an %s habitat." % (my_animal.animal, my_animal.animal_type, my_animal.habitat)
A class defines a type of thing. An instance is one thing of that type. For example, you could say Building is a type of thing.
Let's start with a class named Building:
class Building():
pass
Now, to create an actual building -- an instance -- we call it almost like it was a function:
b1 = Building()
b2 = Building()
b3 = Building()
There, we just created three buildings. They are identical, which isn't very useful. Maybe we can give it a name when we create it, and store it in an instance variable. That requires creating a constructor that takes an argument. All class methods must also take self as its first argument, so our constructor will take two arguments:
class Building():
def __init__(self, name):
self.name = name
Now we can create three different buildings:
b1 = Building("firehouse")
b2 = Building("hospital")
b3 = Building("church")
If we want to create a "driver" class to create three buildings, we can do that pretty easily. If you want to set an instance variable or do some work when you create an instance, you can do that in a constructor. For example, this creates such a class that creates three buildings and stores them in an array:
class Town():
def __init__(self):
self.buildings = [
Building("firehouse"),
Building("hospital"),
Building("church")
]
We now can create a single object that creates three other objects. Hopefully that's enough to get you over the initial hurdle of understanding classes.
OK I will try to answer the main question here: What a class is.
From Google: class /klas/
noun: class; plural noun: classes
1.
a set or category of things having some property or attribute in common and
differentiated from others by kind, type, or quality.
In programming, a class is just that. say, for example you have class Dog. Dogs bark "ruf ruff".
We can define the dog class in python using just that information.
class Dog:
def bark(self):
print "ruf ruff"
To use the class, it is instantiated by calling () its constructor:
Spot = Dog()
We then want Spot to bark, so we call a method of the class:
Spot.bark()
To further explain the details of the code here would be to go outside of the scope of this question.
Further reading:
http://en.wikipedia.org/wiki/Instance_%28computer_science%29
http://en.wikipedia.org/wiki/Method_%28computer_programming%29
As a direct answer:
class Zoo(object):
def __init__(self, name="Python Zoo"):
self.name = name
self.animals = list()
def getAnimal(self,index):
index = index - 1 # account for zero-indexing
try:
print("Animal is {0.name}\n Diet: {0.diet}\n Habitat: {0.habitat}".format(
self.animals[index]))
except IndexError:
print("No animal at index {}".format(index+1))
def listAnimals(self,index):
for i,animal in enumerate(self.animals, start=1):
print("{i:>3}: {animal.name}".format(i=i,animal=animal))
class Animal(object):
def __init__(self, name=None, diet=None, habitat=None):
if any([attr is None for attr in [name,diet,habitat]]):
raise ValueError("Must supply values for all attributes")
self.name = name
self.diet = diet
self.habitat = habitat
class ZooDriver(object):
def __init__(self):
self.zoo = Zoo()
self.zoo.animals = [Animal(name="Giraffe", diet="Herbivore", habitat="Outside"),
Animal(name="Lion", diet="Carnivore", habitat="Inside"),
Animal(name="Bear", diet="Herbivore", habitat="Inside")]
def run(self):
while True:
print("1. List Animals")
print("2. Get information about an animal (by index)"
print("3. Quit")
input_correct = False
while not input_correct:
in_ = input(">> ")
if in_ in ['1','2','3']:
input_correct = True
{'1':self.zoo.listAnimals,
'2':lambda x: self.zoo.getAnimal(input("index #: ")),
'3': self.exit}[in_]()
else:
print("Incorrect input")
def exit(self):
return
if __name__ == "__main__":
ZooDriver().run()
I haven't actually run this code so some silly typos may have occurred and the usual "off-by-one" errors (oops), but I'm fairly confident in it. It displays a lot of concepts your instructor won't expect you to have mastered yet (such as string formatting, most likely, and almost certainly hash tables with lambdas). For that reason, I STRONGLY recommend you not copy this code to turn in.

Categories

Resources