how to define a class variable in python code example
Example 1: declare class python
# To create a simple class:
class Shape:
def __init__():
print("A new shape has been created!")
pass
def get_area(self):
pass
# To create a class that uses inheritance and polymorphism
# from another class:
class Rectangle(Shape):
def __init__(self, height, width): # The constructor
super.__init__()
self.height = height
self.width = width
def get_area(self):
return self.height * self.width
Example 2: python classes
class Box(object): #(object) ending not required
def __init__(self, color, width, height): # Constructor: These parameters will be used upon class calling(Except self)
self.color = color # self refers to global variables that can only be used throughout the class
self.width = width
self.height = height
self.area = width * height
def writeAboutBox(self): # self is almost always required for a function in a class, unless you don't want to use any of the global class variables
print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
greenSquare = Box("green", 10, 10) #Creates new square
greenSquare.writeAboutBox() # Calls writeAboutBox function of greenSquare object
Example 3: class python
class A: # define your class A
.....
class B: # define your class B
.....
class C(A, B): # subclass of A and B
obj = C() #to create instance
# issubclass(sub, sup) boolean function returns true if the given
# subclass sub is indeed a subclass of the superclass sup
# isinstance(obj, Class) boolean function returns true if obj is an
# instance of class Class or is an instance of a subclass of Class