Class
Class
Objects
Python Classes and Objects are the two main aspects of object-
oriented programming (OOPs).
Each car was built from the same set of blueprints and therefore
contains the same components. In object-oriented terms, we say
that your car is an instance (object) of the class Car.
For example, for any bank employee who want to fetch the customer details
online would go to customer class, where all its attributes like transaction
details, withdrawal and deposit details, outstanding debt, etc. would be listed
out.
class Car:
pass
class myClass():
Step 2) Inside classes, you can define functions or methods that are part of
this class
Step 3) Everything in a class is indented, just like the code in the function,
loop, if statement, etc. Anything not indented is not in the class
Class myClass():
Def method1(self):
Print(‘Language’)
Def method2(self, someString):
Print(‘Python Developer’ + someString)
The self-argument refers to the object itself. Hence the use of the word
self. So inside this method, self will refer to the specific instance of this
object that's being operated on.
Self is the name preferred by convention by Pythons to indicate the first
parameter of instance methods in Python. It is part of the Python syntax
to access members of objects
Step 4) To make an object of the class
c = myClass()
Step 5) To call a method in a class
c.method1()
c.method2(" Testing is fun")
def main():
# exercise the class methods
c = myClass ()
c.method1()
c.method2(" Testing is fun")
if __name__== "__main__":
main()
How Inheritance works
Inheritance is a feature used in object-oriented programming; it refers to
defining a new class with less or no modification to an existing class. The new
class is called derived class and from one which it inherits is called the base.
Python supports inheritance; it also supports multiple inheritances. A class
can inherit attributes and behavior methods from another class called
subclass or heir class.
class DerivedClass(BaseClass):
body_of_derived_class
class childClass(myClass):
#def method1(self):
#myClass.method1(self);
#print ("childClass Method1")
def method2(self):
print("childClass method2")
def main():
# exercise the class methods
c2 = childClass()
c2.method1()
#c2.method2()
if __name__== "__main__":
main()
Notice that the in childClass, method1 is not defined but it is derived from the
parent myClass. The output is "Python."
You can call a method of the parent class using the syntax
ParentClassName.MethodName(self)
Python Constructors
A constructor is a class function that instantiates an object to predefined
values.
It begins with a double underscore (_). It __init__() method
class User:
name = ""
def sayHello(self):
print("Welcome to Python, " + self.name)
User1 = User("Students")
User1.sayHello()
Python 2 Example
Summary:
"Class" is a logical grouping of functions and data. Python class provides all
the standard features of Object Oriented Programming.