<< Back to PYTHON
Python Class Examples: Init and Self
Use the class keyword. Call the init method to initialize a class.Class. In the distance a castle stands. It has many functions—it has a moat, it has walls, it guards the city. It keeps out invaders.
Like a castle, a class in Python has functions (defs). A castle guards the town. A class guards its data. Classes are an abstraction.
Init example. This program creates a class. It uses the class keyword and provides two methods. The __init__ method is special. It is a constructor.
Note: Init receives parameters and assigns fields to the new class instance. It can validate arguments, do computations, call methods.
Box: In the expression Box(10, 2), we create a new instance of the Box class. Its width is set to 10. And its height is set to 2.
Area: The area() method will return 20. This is based on the values stored in memory, set by init.
Python program that uses class
class Box:
def area(self):
return self.width * self.height
def __init__(self, width, height):
self.width = width
self.height = height
# Create an instance of Box.
x = Box(10, 2)
# Print area.
print(x.area())
Output
20
Inheritance. A class can inherit from one or more other classes. The class we want to derive from must be defined. The derived class is specified in the parentheses after the class name.
Here: Class B derives from class A. In the statements after the classes, we call size (from class B) and width (from class A).
Size: This def method is found directly on class B. It does not exist on class A.
Width: This is found by checking the base class of class B, which is class A. Width is a method on class A.
Warning: Circular class inheritance is not possible. If B and A both derive from each other, we will get a NameError.
Python program that uses class inheritance
class A:
def width(self):
print("a, width called")
class B(A):
def size(self):
print("b, size called")
# Create new class instance.
b = B()
# Call method on B.
b.size()
# Call method from base class.
b.width()
Output
b, size called
a, width called
Two underscores. In a class, some members have two underscores at the start of their names. These are special. The Python language treats them as private.
And: Private members can be accessed outside the class, but we must add _ClassName to the start.
Here: In class A, we have a field called __value. We must reference this as _A__value outside of the class, but can use __value inside.
Python program that uses two-underscore variable
class A:
# Init.
def __init__(self, value):
self.__value = value
# Two-underscore name.
__value = 0
# Create the class.
a = A(5)
# [1] Cannot use two-underscore name.
# print(a.__value)
# [2] Must use mangled name.
print(a._A__value)
Output
5
Issubclass. This determines if one class is derived from another. With this built-in method, we pass two class names (not instances).
Return: If the first class inherits from the second, issubclass returns true. Otherwise it returns false.
Tip: This is rarely useful to know: a class is considered a subclass of itself. The third issubclass call shows this.
Python program that uses issubclass
class A:
def hello(self):
print("A says hello")
class B(A):
def hello(self):
print("B says hello")
# Use the derived class.
b = B()
b.hello()
# See if B inherits from A.
if issubclass(B, A):
print(1)
# See if A inherits from B.
if issubclass(A, B):
# Not reached.
print(2)
# See if A inherits from itself.
if issubclass(A, A):
print(3)
Output
B says hello
1
3
Isinstance. When the first argument (a variable) is an instance of the second argument (a class), isinstance returns true. It will also return true if the class is a base class.
Here: For some variables, like lists, the class name may not be specified in the program. But we can still test for "list" this way.
Python program that uses isinstance
class A:
def welcome(self):
# Not called.
print("Welcome")
# This is an instance of A.
a = A()
if isinstance(a, A):
print(1)
# This is an instance of the list class.
b = [1, 2, 3]
if isinstance(b, A):
# Not reached.
print(2)
if isinstance(b, list):
print(3)
Output
1
3
Repr. This accesses the __repr__ method from a class. Repr stands for "representation." It converts an object into a string representation. Here we display Snake instances in a special way.
Tip: We return a string from the repr method. The print method automatically calls an object's __repr__ method.
And: We can call repr to force the __repr__ method to be used. This lets us store the representation string in a variable.
Python program that uses repr
class Snake:
def __init__(self, type):
self.type = type
def __repr__(self):
return "Snake, type = " + self.type
# Create Snake instance.
# ... Print its repr.
s = Snake("Anaconda")
print(s)
# Get repr of Snake.
value = repr(s)
print(value)
Output
Snake, type = Anaconda
Snake, type = Anaconda
Property. A property gets and sets a value. It is just like a method, but uses simpler syntax. A property can be assigned like a variable. This causes the setter method to be executed.
Here: We pass two arguments to the property built-in. We specify getname as the getter, and setname as the setter.
Tip: Any code statements can be used in getters and setters. Here we capitalize the string passed to setname.
Snake: We create a Snake class instance. Then we assign the "name" property. This invokes the setname method of the Snake class.
Finally: We print the value of the name property. This invokes the getname method.
Python program that uses property
class Snake:
def getname(self):
return self._name
def setname(self, value):
# When property is set, capitalize it.
self._name = value.capitalize()
name = property(getname, setname)
# Create a snake instance.
s = Snake()
# Set name property.
s.name = "rattle"
# Get name property.
print(s.name)
Output
Rattle
Super. With the super() built-in, we can get the parent of a class. This gets the immediate ancestor. Here we call super() within the Circle class, which references its parent class, Shape.
Print: The name method from Circle prints "Circle." Then name() from Shape is also called.
Python program that uses super
class Shape:
def name(self):
print("Shape")
class Circle(Shape):
def name(self):
print("Circle")
# Call name method from parent class.
super().name()
# Create Circle and call name.
c = Circle()
c.name()
Output
Circle
Shape
Hash. When comparing objects, a hash code can be used for more speed. A dictionary uses hashes. With __hash__ we implement custom hash computations. A unique value is a good hash.
Here: In this program two Snake objects, with the same names and colors, are created. The unique_id is used to compute the hash.
Python program that uses hash on class
class Snake:
def __init__(self, name, color, unique_id):
self.name = name
self.color = color
self.unique_id = unique_id
def __hash__(self):
# Hash on a unique value of the class.
return int(self.unique_id)
# Hash now is equal to the unique ID values used.
p = Snake("Python", "green", 55)
print(hash(p))
p = Snake("Python", "green", 105)
print(hash(p))
Output
55
105
Id method. Every object has an id. This is unique to the instance. Its exact number is an implementation detail and will vary between program executions. Here we look at class ids.
Note: Ids may be reused when objects are removed by the garbage collector and are not in use. They are rarely useful in code.
Python program that uses id
class Cat:
def __init__(self, color):
self.color = color
cat1 = Cat("black")
cat2 = Cat("orange")
# Each object has a unique id.
# ... The ids may vary between runs.
print(id(cat1))
print(id(cat2))
Output
4353403328
4353403384
Classmethod, staticmethod. Python supports special method types (like static methods). These are class methods and static methods.
classmethod
Type. Built-in methods can create and modify types with statements. The type built-in can replace the "class" declaration. With setattr and getattr we add or load fields.
Type
Types, instances. With a class definition, we outline a type. These classes are templates. They must be created as instances (through __init__) to be used. Types are not instances.
Models: In programming, we specify models as templates. And in executable statements, we bring those templates into life (as instances).
In a class, we store data, as in fields. And we also provide method implementations, as with the ref-keyword. This provides an important level of abstraction.
Some concepts. Classes let us easily link data to behavior. They are building blocks in our Python programs. With them, we develop more complex models.
Related Links:
- Python global and nonlocal
- Python not: If Not True
- Python Convert Decimal Binary Octal and Hexadecimal
- Python Tkinter Scale
- Python Tkinter Scrollbar
- Python Tkinter Text
- Python History
- Python Number: random, float and divmod
- Python Tkinter Toplevel
- Python Tkinter Spinbox
- Python Tkinter PanedWindow
- Python Tkinter LabelFrame
- Python Tkinter MessageBox
- Python Website Blocker
- Python Console Programs: Input and Print
- Python Display Calendar
- Python Check Number Odd or Even
- Python readline Example: Read Next Line
- Python Anagram Find Method
- Python Any: Any Versus All, List Performance
- Python Filename With Date Example (date.today)
- Python Find String: index and count
- Python filter (Lambda Removes From List or Range)
- Python ASCII Value of Character
- Python Sum Example
- Python make simple Calculator
- Python Add Two Matrices
- Python Multiply Two Matrices
- Python SyntaxError (invalid syntax)
- Python Transpose Matrix
- Python Remove Punctuation from String
- Python Dictionary items() method with Examples
- Python Dictionary keys() method with Examples
- Python Textwrap Wrap Example
- Python Dictionary popitem() method with Examples
- Python Dictionary pop() method with Examples
- Python HTML: HTMLParser, Read Markup
- Python Tkinter Tutorial
- Python Array Examples
- Python ord, chr Built Ins
- Python Dictionary setdefault() method with Examples
- Python Dictionary update() method with Examples
- Python Dictionary values() method with Examples
- Python complex() function with Examples
- Python delattr() function with Examples
- Python dir() function with Examples
- Python divmod() function with Examples
- Python Loops
- Python for loop
- Python while loop
- Python enumerate() function with Examples
- Python break
- Python continue
- Python dict() function with Examples
- Python pass
- Python Strings
- Python Lists
- Python Tuples
- Python Sets
- Python Built-in Functions
- Python filter() function with Examples
- Python dict Keyword (Copy Dictionary)
- Python Dictionary Order Benchmark
- Python Dictionary String Key Performance
- Python 2D Array: Create 2D Array of Integers
- Python Divmod Examples, Modulo Operator
- bin() in Python | Python bin() Function with Examples
- Python Oops Concept
- Python Object Classes
- Python Constructors
- Python hash() function with Examples
- Python Pandas | Python Pandas Tutorial
- Python Class Examples: Init and Self
- Python help() function with Examples
- Python IndentationError (unexpected indent)
- Python Index and Count (Search List)
- Python min() function with Examples
- Python classmethod and staticmethod Use
- Python set() function with Examples
- Python hex() function with Examples
- Python id() function with Examples
- Python sorted() function with Examples
- Python next() function with Examples
- Python Compound Interest
- Python List insert() method with Examples
- Python Datetime Methods: Date, Timedelta
- Python setattr() function with Examples
- Python 2D List Examples
- Python Pandas Data operations
- Python Def Methods and Arguments (callable)
- Python slice() function with Examples
- Python Remove HTML Tags
- Python input() function with Examples
- Python enumerate (For Index, Element)
- Python Display the multiplication Table
- Python int() function with Examples
- Python Error: Try, Except and Raise
- Python isinstance() function with Examples
- Python oct() function with Examples
- Python startswith, endswith Examples
- Python List append() method with Examples
- Python NumPy Examples (array, random, arange)
- Python Replace Example
- Python List clear() method with Examples
- Python List copy() method with Examples
- Python Lower Dictionary: String Performance
- Python Lower and Upper: Capitalize String
- Python Dictionary Examples
- Python map Examples
- Python Len (String Length)
- Python Padding Examples: ljust, rjust
- Python Type: setattr and getattr Examples
- Python String List Examples
- Python String
- Python Remove Duplicates From List
- Python If Examples: Elif, Else
- Python Programs | Python Programming Examples
- Python List count() method with Examples
- Python List extend() method with Examples
- Python List index() method with Examples
- Python List pop() method with Examples
- Python Palindrome Method: Detect Words, Sentences
- Python Path: os.path Examples
- Python List remove() method with Examples
- Python List reverse() method with Examples
- Top 50+ Python Interview Questions (2021)
- Python List sort() method with Examples
- Python sort word in Alphabetic Order
- abs() in Python | Python abs() Function with Examples
- Python String | encode() method with Examples
- all() in Python | Python all() Function with Examples
- any() in Python | Python any() Function with Examples
- Python Built In Functions
- ascii() in Python | Python ascii() Function with Examples
- Python bytes, bytearray Examples (memoryview)
- bool() in Python | Python bool() Function with Examples
- bytearray() in Python | Python bytearray() Function with Examples
- Python Caesar Cipher
- bytes() in Python | Python bytes() Function with Examples
- Python Sum of Natural Numbers
- callable() in Python | Python callable() Function with Examples
- Python Set add() method with Examples
- Python Set discard() method with Examples
- Python Set pop() method with Examples
- Python math.floor, import math Examples
- Python Return Keyword (Return Multiple Values)
- Python while Loop Examples
- Python Math Examples
- Python Reverse String
- Python max, min Examples
- Python pass Statement
- Python Set remove() method with Examples
- Python Dictionary
- Python Functions
- Python String | capitalize() method with Examples
- Python String | casefold() method with Examples
- Python re.sub, subn Methods
- Python subprocess Examples: subprocess.run
- Python Tkinter Checkbutton
- Python Tkinter Entry
- Python String | center() method with Examples
- Python Substring Examples
- Python pow Example, Power Operator
- Python Lambda
- Python Files I/O
- Python Modules
- Python String | count() method with Examples
- Python String | endswith() method with Examples
- Python String | expandtabs() method with Examples
- Python Prime Number Method
- Python String | find() method with Examples
- Python String | format() method with Examples
- Python String | index() method with Examples
- Python String | isalnum() method with Examples
- Python String | isalpha() method with Examples
- Python String | isdecimal() method with Examples
- Python Pandas Sorting
- Python String | isdigit() method with Examples
- Python Convert Types
- Python String | isidentifier() method with Examples
- Python Pandas Add column to DataFrame columns
- Python String | islower() method with Examples
- Python Pandas Reading Files
- Python Right String Part
- Python IOError Fix, os.path.exists
- Python Punctuation and Whitespace (string.punctuation)
- Python isalnum: String Is Alphanumeric
- Python Pandas Series
- Python Pandas DataFrame
- Python Recursion Example
- Python ROT13 Method
- Python StringIO Examples and Benchmark
- Python Import Syntax Examples: Modules, NameError
- Python in Keyword
- Python iter Example: next
- Python Round Up and Down (Math Round)
- Python List Comprehension
- Python Collection Module
- Python Math Module
- Python OS Module
- Python Random Module
- Python Statistics Module
- Python String Equals: casefold
- Python Sys Module
- Top 10 Python IDEs | Python IDEs
- Python Arrays
- Python Magic Method
- Python Stack and Queue
- Python MySQL Environment Setup
- Python MySQL Database Connection
- Python MySQL Creating New Database
- Python MySQL Creating Tables
- Python Word Count Method (re.findall)
- Python String Literal: F, R Strings
- Python MySQL Update Operation
- Python MySQL Join Operation
- Python Armstrong Number
- Learn Python Tutorial
- Python Factorial Number using Recursion
- Python Features
- Python Comments
- Python if else
- Python Translate and Maketrans Examples
- Python Website Blocker | Building Python Script
- Python Itertools Module: Cycle and Repeat
- Python Operators
- Python Int Example
- Python join Example: Combine Strings From List
- Python Read CSV File
- Python Write CSV File
- Python Read Excel File
- Python Write Excel File
- Python json: Import JSON, load and dumps
- Python Lambda Expressions
- Python Print the Fibonacci sequence
- Python format Example (Format Literal)
- Python Namedtuple Example
- Python SciPy Tutorial
- Python Applications
- Python KeyError Fix: Use Dictionary get
- Python Resize List: Slice and Append
- Python String | translate() method with Examples
- Python Copy List (Slice Entire List)
- Python None: TypeError, NoneType Has No Length
- Python MySQL Performing Transactions
- Python String | isnumeric() method with Examples
- Python MongoDB Example
- Python String | isprintable() method with Examples
- Python Tkinter Canvas
- Python String | isspace() method with Examples
- Python Tkinter Frame
- Python Tkinter Label
- Python Tkinter Listbox
- Python String | istitle() method with Examples
- Python Website Blocker | Script Deployment on Linux
- Python Website Blocker | Script Deployment on Windows
- Python String | isupper() method with Examples
- Python String split() method with Examples
- Python Slice Examples: Start, Stop and Step
- Python String | join() method with Examples
- Python String | ljust() method with Examples
- Python Sort by File Size
- Python Arithmetic Operations
- Python String | lower() method with Examples
- Python Exception Handling | Python try except
- Python Date
- Python Regex | Regular Expression
- Python Sending Email using SMTP
- Python Command Line Arguments
- Python List Comprehension Examples
- Python Assert Keyword
- Python Set Examples
- Python Fibonacci Sequence
- Python Maze Pathfinding Example
- Python Memoize: Dictionary, functools.lru_cache
- Python Timeit, Repeat Examples
- Python Strip Examples
- Python asyncio Example: yield from asyncio.sleep
- Python String Between, Before and After Methods
- Python bool Use (Returns True or False)
- Python Counter Example
- Python frozenset: Immutable Sets
- Python Generator Examples: Yield, Expressions
- Python CSV: csv.reader and Sniffer
- Python globals, locals, vars and dir
- Python abs: Absolute Value
- Python gzip: Compression Examples
- Python Function Display Calendar
- Python Display Fibonacci Sequence Recursion
- Python String | lstrip() method with Examples
- Python del Operator (Remove at Index or Key)
- Python String | partition() method with Examples
- Python String | replace() method with Examples
- Python Zip Examples: Zip Objects
- Python String | rfind() method with Examples
- Python String | rindex() method with Examples
- Python String rjust() method with Examples
- Python String rpartition() method with Examples
- Python String rsplit() method with Examples
- Python Area Of Triangle
- Python Quadratic Equation
- Python swap two Variables
- Python Generate Random Number
- Python Convert Kilometers to Miles
- Python Convert Celsius to Fahrenheit
- Python Check Number Positive Negative or Zero
- Python Check Leap Year
- Python Check Prime Number
- Top 40 Python Pandas Interview Questions (2021)
- Python Check Armstrong Number
- Python SQLite Example
- Python Tkinter Button
- Python Find LCM
- Python Find HCF
- Python Tuple Examples
- Python String | rstrip() method with Examples
- Python String splitlines() method with Examples
- Python String | startswith() method with Examples
- Python String | swapcase() method with Examples
- Python Truncate String
- Python String | upper() method with Examples
- Python for: Loop Over String Characters
- Python String | zfill() method with Examples
- Python Sort Examples: Sorted List, Dictionary
- Python XML: Expat, StartElementHandler
- Python Urllib Usage: Urlopen, UrlParse
- Python File Handling (with open, write)
- Python Example
- Python variables
- Python Random Numbers: randint, random.choice
- Python assert, O Option
- Python Data Types
- Python keywords
- Python literals
- Python MySQL Insert Operation
- Python MySQL Read Operation
- Python ascii Example
- Python ASCII Table Generator: chr
- Python Range: For Loop, Create List From Range
- Python re.match Performance
- Python re.match, search Examples
- Python Tkinter Menubutton
- Python Tkinter Menu
- Python Tkinter Message
- Python Tkinter Radiobutton
- Python List Examples
- Python Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf