[英]How can I write the code in such a way that multiple functions get created but I don't have to write the same code again and again?
[英]Can I somehow merge these classes such that I don't have to write this again and again and my python code doesn't get redundant
import datetime
# I AM CREATING A BIKE RENTAL SYSTEM USING OOP IN PYTHON AND SOMEHOW I SEE MYSELF REPEATING SAME CONTENTS IN METHODS, CAN I SOMEHOW WRITE THIS IN BETTER FORMAT WHICH ISNT REDUNDANT? (I AM NEW TO OOP)
class BikeRental:
def __init__(self, stock=0):
#creating instances of bike rental shop
self.stock = stock
def displayStock(self):
#displaying currently available bikes to rent
print(f'We currently have {self.stock} bikes available for rent')
return self.stock
def BikeOnHourly(self, input):
#rents bike on hourly basis
if input < 0:
print('Number of bikes should be positive!')
return None
elif input > self.stock:
print(f'Sorry we have {self.stock} bikes available right now!')
return None
else:
now = datetime.datetime.now()
print(f'you have rented {input} bike/bikes on hourly basis today'
f'at {now.hour} on {now.date()}')
print('you will be charged 5$ per bike per hour.')
print('Have a great and healthy day!')
self.stock -= input
return now
def BikeOnDailyBasis(self, n):
if n< 0:
print('Number of bikes should be positive!')
return None
elif n >self.stock:
print(f'Sorry we have {self.stock} bikes available right now!')
else:
now = datetime.datetime.now()
print(f'you have rented {n} bike/bikes on hourly basis today'
f'at {now.hour} on {now.date()}')
print('you will be charged 5$ per bike per hour.')
print('Have a great and healthy day!')
self.stock -= n
return now
我假設您要問的是重復 function,而不是 class。 如果是這樣,這樣的事情可能會有所幫助,其想法是讓不同的函數調用具有不同參數基礎的 BikeOnBasis function。 另請參閱多態性以獲取有關以更結構化的方式執行此類操作的信息。
import datetime
# I AM CREATING A BIKE RENTAL SYSTEM USING OOP IN PYTHON AND SOMEHOW I SEE MYSELF REPEATING SAME CONTENTS IN METHODS, CAN I SOMEHOW WRITE THIS IN BETTER FORMAT WHICH ISNT REDUNDANT? (I AM NEW TO OOP)
class BikeRental:
def __init__(self, stock=0):
#creating instances of bike rental shop
self.stock = stock
def displayStock(self):
#displaying currently available bikes to rent
print(f'We currently have {self.stock} bikes available for rent')
return self.stock
def BikeOnHourly(self, n):
self.BikeOnBasis(n, 'hourly')
def BikeOnDailyBasis(self, n):
self.BikeOnBasis(n, 'daily')
def BikeOnBasis(self, n, basis):
if n< 0:
print('Number of bikes should be positive!')
return None
elif n > self.stock:
print(f'Sorry we have {self.stock} bikes available right now!')
else:
now = datetime.datetime.now()
print(f'you have rented {n} bike/bikes on {basis} basis today'
f'at {now.hour} on {now.date()}')
print('you will be charged 5$ per bike per hour.')
print('Have a great and healthy day!')
self.stock -= n
return now
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.