- Class: A blueprint for creating objects that share common atributes and behaviors. It defines the structure and capabilities that all instances of the class will have.
- Class variable: A variable shared among all instances of a class. It is defined inside the class but outside any method, and it’s not typically used as an instance variable.
- Data member: Class variibles or instance variables that hold data associated with the class and its objects.
- Method overriding: If a method inherited from a parent class does not meet the requirements of the child class, it can be redefined. This process is called overriding.
- Local variable: A variable defined inside a method and accessible only within that method.
- Instance variable: A variable defined inside a class (usually in
__init__) and unique to each instance. It represents the state of an object. - Inheritance: A mechanism where a derived class inherits attributes and methods from a base class. It supports the "is-a" relationship (e.g., a
Dogis anAnimal). - Instantiation: The process of creating a concrete object from a class.
- Method: A function defined inside a class that operates on instances of that class.
- Object: A concrete instance of a class, containing instance variables and methods.
2 Class Definition and Usage
References:
https://docs.python.org/3/tutorial/classes.html
https://www.w3schools.com/python/python_classes.asp
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Item: # Class names usually start with capital letters
"""A simple example class for items."""
kind = 'general' # Class variable shared by all instances
item_count = 0 # Another class variable
def __init__(self, name, price):
self.name = name # Instance variable
self.price = price # Instance variable
Item.item_count += 1 # Increment class variable
def show_count(self):
print("Total items created:", Item.item_count)
def show_info(self):
print("Name:", self.name, ", Price:", self.price)
def greet(self): # Regular method
return 'Hello from Item!'
def identify(self):
print(self)
print(self.__class__)
print("----- Built-in Class Attributes -----")
print("Item.__doc__:", Item.__doc__)
print("Item.__name__:", Item.__name__) # Instances do not have __name__
print("Item.__module__:", Item.__module__)
print("Item.__bases__:", Item.__bases__) # Instances do not have __bases__
print("Item.__dict__:", Item.__dict__)
print("Item.__class__:", Item.__class__)
print("-----------\n")
# Create first instance
i1 = Item("Laptop", 1200)
print("Accessing class attribute:", i1.kind) # Accesses the shared 'kind'
print("Calling a method:", i1.greet())
print("Total item_count %d" % Item.item_count)
print("-----------\n")
print('==== i1.identify() start ====')
i1.identify()
print('==== i1.identify() end ====')
print("-----------\n")
i1.show_count()
i1.show_info()
print("-----------\n")
print("---- Instance built-in attributes ----")
print(i1.__doc__) # Same as Item.__doc__
print(i1.__module__) # __main__
print(i1.__dict__) # {'name': 'Laptop', 'price': 1200}
print(i1.__class__) # <class>
print("-----------\n")
# Reference copy
i2 = i1
print('i2 = i1')
print('i1.show_count():')
i1.show_count() # item_count = 1
print('i2.show_count():')
i2.show_count() # item_count = 1
print("Item.item_count %d" % Item.item_count) # item_count = 1
print("-----------\n")
# Create a second distinct instance
i3 = Item("Monitor", 300)
print('i3 = Item("Monitor", 300)')
print('i1.show_count():')
i1.show_count() # item_count = 2
print('i3.show_count():')
i3.show_count() # item_count = 2
print("Item.item_count %d" % Item.item_count) # item_count = 2
print("-----------\n")
print(id(i1), id(i2), id(i3)) # i1 and i2 share the same id
del i1 # Remove the name binding
del i2
del i3
print('All instances (i1,i2,i3) have been deleted.')
print("Accessing a deleted instance raises: NameError: name 'i1' is not defined")
</class>
3 Execution Output
> python item_demo.py
----- Built-in Class Attributes -----
Item.__doc__: A simple example class for items.
Item.__name__: Item
Item.__module__: __main__
Item.__bases__: (<class 'object'>,)
Item.__dict__: {'__module__': '__main__', '__doc__': 'A simple example class for items.', 'kind': 'general', 'item_count': 0, '__init__': <function Item.__init__ at 0x7f8b1c2bdf70>, 'show_count': <function Item.show_count at 0x7f8b1c2e5040>, 'show_info': <function Item.show_info at 0x7f8b1c2e50d0>, 'greet': <function Item.greet at 0x7f8b1c2e5160>, 'identify': <function Item.identify at 0x7f8b1c2e51f0>, '__dict__': <attribute '__dict__' of 'Item' objects>, '__weakref__': <attribute '__weakref__' of 'Item' objects>}
Item.__class__: <class 'type'>
-----------
Accessing class attribute: general
Calling a method: Hello from Item!
Total item_count 1
-----------
==== i1.identify() start ====
<__main__.Item object at 0x7f8b1c32e490>
<class '__main__.Item'>
==== i1.identify() end ====
-----------
Total items created: 1
Name: Laptop , Price: 1200
-----------
---- Instance built-in attributes ----
A simple example class for items.
__main__
{'name': 'Laptop', 'price': 1200}
<class '__main__.Item'>
-----------
i2 = i1
i1.show_count():
Total items created: 1
i2.show_count():
Total items created: 1
Item.item_count 1
-----------
i3 = Item("Monitor", 300)
i1.show_count():
Total items created: 2
i3.show_count():
Total items created: 2
Item.item_count 2
-----------
139954187023504 139954187023504 139954187023744
All instances (i1,i2,i3) have been deleted.
Accessing a deleted instance raises: NameError: name 'i1' is not defined