I'm trying the implement the following into Python:
NAMES = {"fn" => ["James", "John", "John"], "ln" => ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator
def self.generate
new.to_s
end
def initialize
#fn = NAMES['fn'].sample
#ls = NAMES['ln'].sample
end
def to_s
#fn + " " + #ls
end
end
Which returns:
>> RandomNameGenerator.generate
=> "James Smith"
>> RandomNameGenerator.generate
=> "John Johnson"
My code thus far looks like:
import random
NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator(object):
#classmethod
def generate(cls):
RandomNameGenerator().__str__
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
>>> RandomNameGenerator.generate()
>>> print(RandomNameGenerator.generate())
None
I feel like Ruby's new.to_s isn't the same as Python'sRandomNameGenerator().__str__. What am I not understanding?
You don't return anything in the generate method. Also the __init__ code is called when you initialiaze the class, in you case you are not doing it. You are just calling the class static method. In order to make your code work you have to create a new instance of the RandomNameGenerator in the generate method.
class RandomNameGenerator(object):
#classmethod
def generate(cls):
return cls()
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
You are not returning from the method generate():
import random
NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator(object):
#classmethod
def generate(cls):
return str(cls())
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
for i in range(5):
print(RandomNameGenerator.generate())
OUTPUT:
John Johnson
John Brown
James Johnson
James Brown
James Johnson
Related
I have an assignment that asks this:
4)Add a method to filter out tiger in the zoo and look at them. Use regex to achieve this functionality.
Hint: you will have to go over all the animals in the zoo.
I'm not sure how to search a list of class object names using regex. Any hints here would be appreciated greatly!
import functools
import re
class Animal:
def __init__(self):
self.__numberOfLegs = 4
self.__numberOfHands = 0
def look(self):
return "\nNumber of hands: {hand}, Number of legs: {leg}".format(
hand=self.__numberOfHands, leg=self.__numberOfLegs)
class Bird:
def __init__(self):
self.__numberOfLegs = 2
self.__numberOfWings = 2
def look(self):
return "\nNumber of wings: {wing}, Number of legs: {leg}".format(
wing=self.__numberOfWings, leg=self.__numberOfLegs)
class Feline(Animal):
def __init__(self):
Animal.__init__(self)
self.__characteristic = "Felines belong to the cat family"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Tiger(Feline):
def __init__(self):
Feline.__init__(self)
self.__characteristic = "Tigers can roar and are lethal predators\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class WildCat(Feline):
def __init__(self):
Feline.__init__(self)
self.__characteristic = "Wild cats can climb trees\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class Canine(Animal):
def __init__(self):
Animal.__init__(self)
self.__characteristic = "Canines belong to the dog family"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Wolf(Canine):
def __init__(self):
Canine.__init__(self)
self.__characteristic = "Wolves hunt in packs and have a leader\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class FlightBird(Bird):
def __init__(self):
Bird.__init__(self)
self.__characteristic = "Flight birds fly and hunt for food"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Eagle(FlightBird):
def __init__(self):
FlightBird.__init__(self)
self.__characteristic = "Eagles fly extremely high and can see their prey from high up in the sky\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class Zoo:
def __init__(self):
self.__animalList = list()
self.__birdList = list()
def add(self, living_thing):
if not isinstance(living_thing, Animal) and not isinstance(living_thing, Bird):
raise Exception("Only animals and birds can be passed")
try:
if isinstance(living_thing, Animal):
if len(list(filter(lambda a: type(a) == type(living_thing), self.__animalList))) == 0:
if len(self.__animalList) < 2:
self.__animalList.append(living_thing)
print("Animal Added")
else:
print("Zoo full for animals")
else:
print("Creature already in zoo")
elif isinstance(living_thing, Bird):
if len(self.__birdList) < 1:
self.__birdList.append(living_thing)
print("Bird Added")
else:
print("Zoo full for birds")
except Exception:
print("An error has occurred")
else:
print("Completed without errors\n")
def looking(self):
print(Zoo.__look_all_contents(self.__animalList + self.__birdList))
def find_canine(self):
canine_in_zoo = map(lambda h: h.look(), list(filter(lambda g: isinstance(g, Canine), self.__animalList)))
print(*canine_in_zoo)
def find_tiger(self):
#staticmethod
def __look_all_contents(combined_lists):
if len(list(combined_lists)) == 0:
return "Zoo is empty"
string_reduce_map = functools.reduce(lambda x, y: x + y, map(lambda j: j.look(), list(combined_lists)))
return string_reduce_map
zoo = Zoo()
zoo.add(Tiger())
zoo.add(Wolf())
zoo.add(Eagle())
zoo.looking()
zoo.find_canine()
zoo.find_tiger()
How do I search the list_of_classes with regex?
I've created a class named Patient that has attributes for patient information. I'm supposed to use an accessor and mutator method for each attribute. Then I've created another file to access the class and insert patient information to print. Every time I print I don't get what I expect but I get <Assignment4Q1PatientClass2nd.Patient object at 0x000002429E038A00>.
Here's what is on my first file (File name is Assignment4Q1PatientClass2nd):
class Patient:
def __init__(self, fname, mname, lname, address, city, state, zipcode, phone, ename, ephone):
self._fname = fname #first name
self._mname = mname #middle name
self._lname = lname #last name
self._address = address #address
self._city = city #city for address
self._state = state #state for address
self._zipcode = zipcode #zipcode for address
self._phone = phone #phone number
self._ename = ename #emergency name
self._ephone = ephone #emergency phone
#add patient information
def addFirstName(self, firstname):
self._fname = self._fname + firstname
def addMiddleName(self, middlename):
self._mname = self._mname + middlename
def addLastName(self, lastname):
self._lname = self._lname + lastname
def addAddress(self, locaddress):
self._address = self._address + locaddress
def addCity(self, cityname):
self._city = self._city + cityname
def addState(self, statename):
self._state = self._state + statename
def addZipcode(self, zipcodenum):
self._zipcode = self._zipcode + zipcodenum
def addPhone(self, phonenum):
self._phone = self._phone + phonenum
def addEName(self, emergencyname):
self._ename = self._ename + emergencyname
def addEPhone(self, emergencyphone):
self._ephone = self._ephone + emergencyphone
#get/return all information of the Patient
def getPatientFirstName(self):
return "First Name:" + self._fname
def getPatientMiddleName(self):
return "Middle Name:" + self._mname
def getPatientLastName(self):
return "Last Name:" + self._lname
def getPatientAddress(self):
return "Address:" + self._address
def getPatientCity(self):
return "City:" + self._city
def getPatientState(self):
return "State:" + self._state
def getPatientZipcode(self):
return "ZIP:" + self._zipcode
def getPatientPhone(self):
return "Phone:" + self._phone
def getPatientEName(self, emergencyname):
return "Emergency Contact:" + self._ename
def getPatientEPhone(self, emergencyphone):
return "Emergency Phone:" + self._ephone
on the second file is:
from Assignment4Q1PatientClass2nd import Patient
pat = Patient("James", "Edward", "Jones", "345 Main Street", "Billings", "Montanna", 59000, "406-555-1212", "Jenny Jones", "406-555-1213")
print(pat)
What did you expect from your print statement?
The class actually don't "know" what to print. You must provide a way to represent that class as a string, so we can print that string.
In practice, we do this by adding a function called "__repr__", the representation of this class. Python automatically identifies this as a especial one, just like "__init__".
Here is a small example to you:
class Patient:
def __init__(self, name):
self._name = name
def getPatientName(self):
return self._name
def __repr__(self):
return "Hey! My name is " + self.getPatientName()
pat = Patient("Dikson")
print(pat)
# Hey! My name is Dikson
Hope it's clear :)
I'm learning python here:
I have created this cars class below and I want to that result go to the list.
What is the most efficiency way to do it?
class Car:
def __init__(self, brand="", price=""):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
import random
carslist = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
car1 = Car()
car1.brand = (random.choice(carslist))
car1.price = (random.randint(1000, 10000))
car2 = Car()
car2.brand = (random.choice(carslist))
car2.price = (random.randint(1000, 10000))
car3 = Car()
car3.brand = (random.choice(carslist))
car3.price = (random.randint(1000, 10000))
car4 = Car()
car4.brand = (random.choice(carslist))
car4.price = (random.randint(1000, 10000))
car5 = Car()
car5.brand = (random.choice(carslist))
car5.price = (random.randint(1000, 10000))
print(car1)
I did try it like this cars1 = car1details cars2 = car2details and list [car1details, car2details] but that's not probably the best way to do it.
Thanks for you help!
The below seems to work nice (__repr__ was added since when we print the cars it is used)
import random
class Car:
def __init__(self, brand="", price=0):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
def __repr__(self):
return str(self.brand) + " " + str(self.price)
cars_models = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = [Car(random.choice(cars_models),random.randint(1000, 10000)) for _ in range(1,8)]
print(cars)
output
[BMW 2008, Volvo 3810, Skoda 8545, Skoda 6715, Ford 9792, Audi 6013, VW 1475]
here is an example of how to append objects to a list by using range()
When you append the Car object you can add variables
class Car(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(Car(i))
from random import randint
class Car():
def __init__(self, name):
self.name= name
self.price = randint(1000, 10000)
def __str__(self):
return f'Car( Name: {self.name} | price {self.price})'
def __repr__(self):
return f'Car( Name: {self.name} | price {self.price})'
carsname = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = []
for name in carsname:
cars.append(Car(name))
Use a basic for :)
So for my last assingment in my python course at uni, I have to write a program consisting of three objects, two of which inherit. I keep running into a snag especially with regards to the last two objects. Here is my code:
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
def __repr__(self):
super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,grade,ID=0,title=""):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
At around line 60 I recieve the error:
TypeError: str returned non-string (type NoneType)
I'm pretty lost as to what is going on.
Your __repr__s don't explicitly return anything. You build up a string, then throw it away, causing None to be implicitly returned instead.
Just add a return:
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
Adjustments to the source code of the original question:
add missing statement at def dropStudent(self,stu):
add missing return expression for def __repr__(self):
adjust signature of StudentCourse(Course) init to def __init__(self,title,ID,grade): to be in line with parent classes and process given statement StudentCourse("History of Nu-Metal",57859,82) as expected
add missing indentions for def main():
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
print("#todo Something is missing here...")
def __repr__(self):
return super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,title,ID,grade):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
main()
Me very very new programmer, I'm new to classes and not sure how to set up a print method for this class. How do I go about setting up a print method for my class here? Thanks for anything!
class travelItem :
def __init__(self, itemID, itemName, itemCount) :
self.id = itemID
self.name = itemName
self.itemCount = itemCount
self.transactions = []
def getID(self) :
return(self, id)
def getName(self) :
return(self.name)
def setName(self, newName) :
self.name = newName
def getAvailableStart(self):
return(self.AvailableStart)
def appendTransaction(self, num) :
self.transactions.append(num)
def getTransactions(self) :
return(self.transactions)
def getReservations(self) :
Additions = 0
for num in self.transactions :
if (num > 0) :
Additions = Additions + num
return(Additions)
def getCancellations(self) :
Subtractions = 0
for num in self.transactions :
if (num < 0) :
Subtractions = Subtractions + num
return(Subtractions)
def getAvailableEnd(self) :
total = self.AvailableStart
for num in self.transactions :
total = total + num
return(total)
Remember that a method is called on an instance of a class, so if you mean to create a true method that just prints a class you can write something like
class Foo(object):
def print_me(self):
print(self)
foo_instance= Foo()
foo_instance.print_me()
But it sounds like you want to customize the output of print(). That is what the built in method __str__ is for, so try this.
class Foo(object):
def __str__(self):
# remember to coerce everything returned to a string please!
return str(self.some_attribute_of_this_foo_instance)
a good example from your code might be
...
def __str__(self):
return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions'
You must use a __str__ special method:
class travelItem:
...
def __str__(self):
return "a string that describe the data I want printed when print(instance of class) is called"