Print(c1) # Invoke _str_(): This is a circle with radius of 2.10 # If this module is imported into another module, _name_ is 'circle' (the module name). # If this module is run under Python interpreter, _name_ is '_main_'. """Return the area of this Circle instance""" Return 'This is a circle with radius of )'.format(self.radius) """Return a descriptive string for this instance, invoked by print() and str()""" Self.radius = radius # Create an instance variable radius """Initializer with default radius of 1.0""" The Circle class shall contain a data attribute radius and a method get_area(), as shown in the following class diagram.Ĭircle.py: The circle module, which defines a Circle class.Ĭlass Circle: # For Python 2 use: "class Circle(object):" """A Circle instance models a circle with a radius""" Let's write a module called circle (to be saved as circle.py), which contains a Circle class. Example 1: Getting Started with a Circle class To construct an instance of a class, invoke the constructor in the form of instance_name = class_name( args). To access an attribute, use "dot" operator in the form of class_name. In UML diagram, objects are represented by 3-compartment boxes: name, data attributes and methods, as shown below: In fact, everything in Python is object, including class object.Īn object contains attributes: data attributes (or static attribute or variables) and dynamic behaviors called methods. Unlike C++/Java, Python supports both class objects and instance objects. An instance is a particular realization of a class. Python OOP Basics OOP BasicsĪ class is a blueprint or template of entities (things) of the same kind. This article is not an introduction to OOP. I assume that you are familiar with the OOP concepts (such as class and instance, composition, inheritance and polymorphism), and you know some OO languages such as Java/C++/C#.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |