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
__init__() function: When an object is created, this function is called to initialize this new object with information. Its first argument must be self and it's called before any other argument in the class.__init()__ are called instance attributes, first parameter is always self. An instance attribute’s value is specific to a particular instance of the class. All Book objects have a title, author, pages and price, but the values for the these attributes will vary depending on the Book instance.__init()__, an instance method’s first parameter is always self. In the above example, get_author() is an instance method.self: Whenever we call a method on a python object, the object itself gets passed as the first argument to the method.__self__(): When you print an object, you get a cryptic message like <__main__.Book object at 0x00aeff70>. We can change this behavior by defining a special instance method called __self__()._discount refers to the fact that this attribute is internal to the class, and should not be used outside the class as logic. Since _discount was not defined during the init function, we first test for it using the hasattr() function.type(object_name) will return the class name. We can use it to compare if two objects are of the same type.isinstance(object_name, class_name) function which will return True/False