Python Fundamentals

Defining Classes


By convention, classnames use CamelCase (sometimes known as PascalCase).

# Class Definition
class Book: 
	def __init__(self, title, author,pages,price):
		# These are instance attributes
		self.title = title
		self.author = author
		self.pages = pages
		self.price = price	

	# Instance Methods
	def get_author(self):
		return self.author

	def getPrice(self):
		if hasattr(self,"_discount"):
			return self.price - (self.price * self._discount)
		else:
			return self.price

	def __self__(self):
		return f"Title: {self.title}, Author: {self.author}"

	# Defining an instance attribute outside of __init__()
	def setDiscount(self,amount):
		self._discount = amount

# Create objects
b1 = Book("War and Peace","Leo Toltstoy",1225, 39.95)
b2 = Book("Black Beauty","Anna Sewell", 234, 29.95)

#Access the value of property
print(b1.title) #War and Peace
print(b1.getPrice()) # Before discount, 39.95
b1.setDiscount(0.25) # Set discount
print(b1.getPrice()) # After discount, 29.9625

Class Methods and Attributes