I am new to OOP and working on an example:
class Vehicle (object):
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def seating_capacity(self, capacity):
return f"The seating capacity of a {self.name} is {capacity} passengers"
class Bus(Vehicle):
def __init__(self, name, max_speed, mileage):
Vehicle.__init__(self, name, max_speed, mileage)
def __str__(self):
return f"Brand: {self.name}, Maximum Speed: {self.max_speed} MPH, Mileage: {self.mileage}"
def seating_capacity(self, capacity = 50):
return super().seating_capacity(capacity = 60)
b = Bus("a", 190, 29)
print(b.seating_capacity())
Here, I don't understand which default value of capacity is preferred. For example when I just write:
def seating_capacity(self, capacity = 50):
return super().seating_capacity(capacity = 60)
I get "The seating capacity of a a is 60 passengers" so this implies super().seating_capacity(capacity = 60) Has more preference and def seating_capacity(self, capacity = 50) is just a fallback value, right?
Then when I try:
def seating_capacity(self, capacity):
return super().seating_capacity(capacity = 60)
According to my understanding, In this case there is no need of fall back value. Yet I get, *TypeError: seating_capacity() missing 1 required positional argument: 'capacity'.
Related
I am attempting to calculate a fare for the 'Vehicle' class, whereby the fare is equal to the seating_capacity of the vehicle, multiplied by 10. My code is as follows:
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
def seating_capacity(self, capacity=4):
self.capacity = capacity
return capacity
def fare(capacity):
fare = capacity * 10
return fare
class Bus(Vehicle):
def __init__(self, max_speed, mileage):
Vehicle.__init__(self, max_speed, mileage)
def seating_capacity(self, capacity=50):
return super().seating_capacity(capacity)
vehicle = Vehicle(240, 18)
print(f"Vehicle total fare is {vehicle.fare()}")
However, when I run the program, I am met with this traceback error:
TypeError: unsupported operand type(s) for *: 'Vehicle' and 'int'
The output should be 40, since the capacity of the vehicle is set to 4 by default. What am I doing wrong?
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
self.capacity = 4
def seating_capacity(self):
return self.capacity
def fare(self):
fare = self.capacity * 10
return fare
class Bus(Vehicle):
def __init__(self, max_speed, mileage):
Vehicle.__init__(self, max_speed, mileage)
def seating_capacity(self, capacity=50):
return super().seating_capacity(capacity)
vehicle = Vehicle(240, 18)
print(f"Vehicle total fare is {vehicle.fare()}")
This is my code. I would like to know how to combine the "_transactions" attributes from 2+ objects.
Could you please help me out?
class Account:
def __init__(self, owner, amount=0):
self.owner = owner
self.amount = amount
self._transactions = []
def add_transaction(self, amount):
if type(amount) != int:
raise ValueError("please use int for amount")
self._transactions.append(amount)
def __add__(self, other):
name = f"{self.owner}&{other.owner}"
starting_amount = self.amount + other.amount
self._transactions += other._transactions
return Account(name, starting_amount)
acc = Account('bob', 10)
acc2 = Account('john')
acc.add_transaction(20)
acc.add_transaction(-20)
acc.add_transaction(30)
acc2.add_transaction(10)
acc2.add_transaction(60)
acc3 = acc + acc2
print(acc3._transactions)
The output should be:
[20, -20, 30, 10, 60]
But instead is:
[]
You should modify the __add__ function in order to sum the transactions; infact when you instatiate a new class, the self._transactions attribute is an empty list by default.
class Account:
def __init__(self, owner: str, amount: int = 0, transactions: list = None):
self.owner = owner
self.amount = amount
self._transactions = [] if transactions is None else transactions
def __add__(self, other):
name = f"{self.owner}&{other.owner}"
starting_amount = self.amount + other.amount
transactions = self._transactions + other._transactions
return Account(name, starting_amount, transactions)
def add_transaction(self, amount):
if type(amount) != int:
raise ValueError("please use int for amount")
self._transactions.append(amount)
acc = Account('bob', 10)
acc2 = Account('john')
acc.add_transaction(20)
acc.add_transaction(-20)
acc.add_transaction(30)
acc2.add_transaction(10)
acc2.add_transaction(60)
acc3 = acc + acc2
print(acc3._transactions)
>>> [20, -20, 30, 10, 60]
I have to use the class method in python to calculate the average age, height, and weight of a list of 2 school classes and compare them.
In order to calculate the average ages, I used the following code:
from statistics import mean
class Student():
counter = 0
def __init__ (self, age, height, weight):
Student.counter += 1
self.age = age
self.height = height
self.weight = weight
class Class_a(Student):
def av_a():
temp = []
for i in range (n):
temp.append(class_a[i].age)
m_a = (mean(temp))
return m_a
class_a = []
n = 2
age_a = ['15', '99']
height_a = ['123', '144']
weight_a = ['33', '28']
for i in range (n):
class_a.append(Class_a(float(age_a[i]), float(height_a[i]), float(weight_a[i])))
print(Class_a.av_a())
It would be highly appreciated if anyone reviews the code and let me know the best way to do such a calculation.
Thank you in advance.
You could replace Class_a with a kind of collection that would hold multiple Student instances. In this case, no need to inherit from Student:
class Student():
def __init__(self, age, height, weight):
self.age = int(age)
self.height = int(height)
self.weight = int(weight)
class Students():
def __init__(self, *students):
self.students = list(students)
# implementation of height() and weight() would be similar
def age(self):
return mean(map(lambda x: x.age, self.students))
def add(self, student):
self.students.append(student)
def __len__(self):
return len(self.students)
This way you can initialize with some students:
students = Students(Student('15', '123', '33'))
And/or add more later:
students.add(Student('99', '144', '28'))
students.add(Student('20', '134', '22'))
You have access to the averages at any time:
print(students.age())
class Student:
def __init__(self, num, age, heigth, weigth):
self.number = num
self.age = age
self.heigth = heigth
self.weigth = weigth
def cal_average(self):
return(sum(self.age)/len(self.age), sum(self.heigth)/len(self.heigth), sum(self.weigth)/len(self.weigth))
example
a = Student(5,[16, 17, 15, 16, 17],[180, 175, 172, 170, 165],[67, 72, 59, 62, 55])
avg1, avg2, avg3 = a.cal_average()
I got the error : TypeError: init() missing 1 required positional argument: 'attack'
class Unit:
def __init__(self, name):
self.name = name
class Power(Unit):
def __init__(self, name, attack):
Unit.__init__(self, name)
self.attack = attack
supatt = attack * 2
print("{0} has a power of {1} and it can develop {1}
of its superpowers".format(self.name, attack, supatt))
class Ground(Power):
def __init__(self, name, attack, velocity, friction):
Power.__init__(self, attack)
self.velocity = velocity
self.friction = friction
totalv = velocity - fiction
print("{0} : Groud Attack. \nTotal Speed : {1}.\n
Power : {2}.".format(self.name, totalv, attack))
class Sky(Power):
def __init__(self, name, attack, skyspeed, airres):
Power.__init__(self, attack)
self.skyspeed = skyspeed
self.airres = airres
totalss = skyspeed - airres
print("{0} : Sky Attack. \nTotal Speed : {1}.\n Power
: {2}.".format(self.name, totalss, attack))
valkyrie = Sky("Valkyrie", 200, 300, 150)
print(valkyrie)
The error comes in the Sky(Power) class where I wrote :
Power.__init__(self, attack)
I thought I already wrote attack here. What is wrong with this code?
You were trying to inherit the Power Class to every other class except for the Unit class.
You want to inherit the classes using the super() function.
class Unit:
def __init__(self, name):
self.name = name
class Power(Unit):
def __init__(self, name, attack):
Unit.__init__(self, name)
self.attack = attack
supatt = attack * 2
print("{0} has a power of {1} and it can develop {1} of its
superpowers".format(self.name, attack, supatt))
class Sky(Power):
def __init__(self, name, attack, skyspeed, airres):
super().__init__(self, attack)
self.skyspeed = skyspeed
self.airres = airres
totalss = skyspeed - airres
print("{0} : Sky Attack. \nTotal Speed : {1}.\n Power:
{2}.".format(self.name, totalss, attack))
class Ground(Power):
def __init__(self, name, attack, velocity, friction):
super().__init__(self, attack)
self.velocity = velocity
self.friction = friction
totalv = velocity - friction
print("{0} : Groud Attack. \nTotal Speed : {1}.\nPower :
{2}.".format(self.name, totalv, attack))
valkyrie = Sky("Valkyrie", 200, 300, 150)
print(valkyrie)
I am trying to complete a series of class definition tasks and can't seem to get past this one. It is part of a 3 part series; the first part asks you to model a library book, which I could complete easily.
The next part is asking to create a Member class to model a library member and include a borrow_book() and a return_book() method, and to get the member's list of all loan books to print out in alphabetical order.
I cannot understand which part I am going wrong on. Could someone possibly point me in the right direction? I have included my code so far below.
class Book(object):
def __init__(self, title, author, copies=1, loan=0):
self.title = title
self.author = author
self.copies = copies
self.loan = loan
def checkbook(self, title):
for book in self.title:
if book.title in self.title:
return book
else:
print("Sorry, Not Available.")
def borrow_book(self):
abc = self.checkbook(title)
print(abc)
self.loan += 1
self.copies -= 1
def return_book(self):
self.loan -= 1
def __str__(self):
r = []
r.append('Title: {}'.format(self.title))
r.append('Author: {}'.format(self.author))
r.append('Copies: {}'.format(self.copies))
r.append('On loan: {}'.format(self.loan))
return '\n'.join(r)
def sort_books(b):
return b.title
class Member(object):
def __init__(self, mid, name, loans=0):
self.mid = mid
self.name = name
self.loans = loans
self.d = {}
def __str__(self, mid, name, loans=0):
r = []
r.append('ID: {}'.format(self.mid))
r.append('Name: {}'.format(self.name))
r.append('Loans: {}'.format(self.loans))
l = ['{}'.format(b) for b in sorted(self.d.values(), key=sort_books)]
return '\n'.join(r)
return '\n'.join(l)