Python 3 object-oriented

Object-Oriented Python 3

Python was designed as an object-oriented language from the beginning. Because of this, creating classes and objects in Python is easy. This section will provide a detailed introduction to Python object-oriented programming.

If you haven’t used an object-oriented programming language before, you may want to first understand some of its basic features. Forming a basic understanding of object-oriented concepts will help you more easily learn Python object-oriented programming.

Next, let’s briefly explore some of the basic features of object-oriented programming.


Introduction to Object-Oriented Technology

  • Class: A class is used to describe a collection of objects with the same attributes and methods. It defines the attributes and methods shared by all objects in the collection. Objects are instances of a class.
  • Method: Functions defined within a class.
  • Class variables: Class variables are public across all instantiated objects. Class variables are defined within the class and outside of function bodies. Class variables are not typically used as instance variables.
  • Data members: Class variables or instance variables are used to handle data related to the class and its instance objects.
  • Method overriding: If a method inherited from a parent class doesn’t meet the needs of a subclass, it can be overridden. This process is called overriding a method.
  • Local variables: Variables defined within a method are only applicable to the current instance of the class.
  • Instance variables: In a class declaration, attributes are represented by variables. These variables are called instance variables. Instance variables are simply variables with the “self” modifier.
  • Inheritance: A derived class inherits the fields and methods of its base class. Inheritance also allows objects of a derived class to be treated as objects of a base class. For example, consider a design where an object of type Dog derives from the class Animal, simulating an “is-a” relationship (for example, Dog is an Animal).
  • Instantiation:Creating an instance of a class, a concrete object of the class.
  • Object:An instance of a data structure defined by a class. An object consists of two data members (class variables and instance variables) and methods.

Compared to other programming languages, Python introduced the class mechanism with minimal new syntax and semantics.

Classes in Python provide all the basic features of object-oriented programming: class inheritance allows multiple base classes, derived classes can override any method in a base class, and methods can call methods of the same name in a base class.

Objects can contain any amount and type of data.

Class Definition

The syntax is as follows:

class ClassName:
<statement-1>
.
.
.
<statement-N>

After a class is instantiated, its attributes can be used. In fact, after creating a class, its attributes can be accessed by using the class name.

Class Objects

Class objects support two operations: attribute reference and instantiation.

Attribute references use the same standard syntax as all attribute references in Python: obj.name.

Once a class object is created, all names in the class namespace are valid attribute names. So if the class definition looks like this:

Example (Python 3.0+)

#!/usr/bin/python3

class MyClass:
""A simple class instance"""
i = 12345
def f(self):
return 'hello world'

# Instantiate the class
x = MyClass()

# Access class attributes and methods
print("Attribute i of MyClass is:", x.i)
print("Method f of MyClass outputs:", x.f())

The above creates a new class instance and assigns it to the local variable x, which is an empty object.

Executing the above program produces the following output:

The value of attribute i in the MyClass class is: 12345
The output of method f in the MyClass class is: hello world

A class has a special method (constructor) called __init__(), which is automatically called when the class is instantiated, as shown below:

def __init__(self):
self.data = []

A class defines a __init__() method, which is automatically called when the class is instantiated. If you instantiate the class MyClass as follows, the corresponding __init__() method will be called:

x = MyClass()

Of course, the __init__() method can have parameters, which are passed to the class instantiation operation through __init__(). For example:

Example (Python 3.0+)

#!/usr/bin/python3

class Complex:

def __init__(self, realpart, imagpart):

self.r = realpart

self.i = imagpart

x = Complex(3.0, -4.5)

print(x.r, x.i) # Output: 3.0 -4.5

self represents the class instance, not the class.

Class methods differ from ordinary functions in only one important way—they must have an additional first argument, which by convention is called self.

class Test:
def prt(self):
print(self)
print(self.__class__)

t = Test()
t.prt()

The execution result of the above example is:

<__main__.Test instance at 0x100771878>
__main__.Test

From the execution result, it is clear that self represents the class instance, indicating the address of the current object, while self.class points to the class.

“self” is not a Python keyword. We can replace it with “geekdoc” and the program will still run normally:

class Test:
def prt(geekdoc):
print(geekdoc)
print(geekdoc.__class__)

t = Test()
t.prt()

The above example produces the following results:

<__main__.Test instance at 0x100771878>
__main__.Test

Class Methods

Within a class, the def keyword is used to define a method. Unlike general function definitions, class methods must include the parameter “self” as the first parameter. “self” represents the class instance.

Example (Python 3.0+)

#!/usr/bin/python3

#Class definition
class people:
#Define basic attributes
name = ''
age = 0
#Define private attributes; private attributes cannot be directly accessed from outside the class
__weight = 0
#Define constructor
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s said: I am %d years old." %(self.name, self.age))

#Instantiate the class
p = people('geekdoc',10,30)
p.speak()

The output of executing the above program is:

geekdoc said: I 10 years old.

Inheritance

Python also supports class inheritance. If a language doesn’t support inheritance, classes would be meaningless. The definition of a derived class is as follows:

class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>

BaseClassName (the base class name in the example) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is very useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Example (Python 3.0+)

#!/usr/bin/python3

#Class definition
class people:
#Define basic attributes
name = ''
age = 0
#Define private attributes; private attributes cannot be directly accessed from outside the class
__weight = 0
#Define the constructor
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s said: I am %d years old." %(self.name, self.age))

#Single inheritance example
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#Call the parent class's constructor
people.__init__(self,n,a,w)
self.grade = g
#Override the parent class's method
def speak(self):
print("%s said: I am %d years old and in %d grade" % (self.name, self.age, self.grade))

s = student('ken',10,60,3)
s.speak()

Executing the above program prints:

ken said: I am 10 years old and in 3rd grade

Multiple Inheritance

Python also supports a limited form of multiple inheritance. The following example shows a class definition for multiple inheritance:

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>

Note the order of the parent classes in the parentheses. If a parent class has the same method name but does not specify it when using it in a subclass, Python searches from left to right.
That is, if a method is not found in a subclass, Python searches from left to right to see if the parent class contains the method.

Example (Python 3.0+)

#!/usr/bin/python3

#Class definition
class people:
#Define basic attributes
name = ''
age = 0
#Define private attributes; private attributes cannot be directly accessed from outside the class
__weight = 0
#Define constructor
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s said: I am %d years old." %(self.name, self.age))

#Single inheritance example
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#Call the parent class's constructor
people.__init__(self,n,a,w)
self.grade = g
#Override the parent class's method
def speak(self):
print("%s said: I am %d years old and in grade %d" % (self.name, self.age, self.grade))

# Another class, preparation before multiple inheritance
class speaker():
topic = ''
name = ''
def __init__(self, n, t):
self.name = n
self.topic = t
def speak(self):
print("My name is %s, I am a speaker, and the topic of my speech is %s" % (self.name, self.topic))

# Multiple inheritance
class sample(speaker, student):
a = ''
def __init__(self, n, a, w, g, t):
student.__init__(self, n, a, w, g)
speaker.__init__(self, n, t)

test = sample("Tim", 25, 80, 4, "Python")
test.speak() # If the method names are the same, the parent class method listed first in the parentheses is called by default.

The output of executing the above program is:

My name is Tim, I am a speaker, and my speech topic is Python.

Method Overriding

If the functionality of your parent class method does not meet your needs, you can override it in a child class. The example is as follows:

Example (Python 3.0+)

#!/usr/bin/python3

class Parent: # Define the parent class
def myMethod(self):
print ('Calling parent class method')

class Child(Parent): # Define the child class
def myMethod(self):
print ('Calling child class method')

c = Child() # Subclass instance
c.myMethod() # Subclass calls overridden method
super(Child, c).myMethod() # Use subclass object to call superclass overridden method

The super() function is used to call a method of the parent class (superclass).

The output of executing the above program is:

Calling a subclass method
Calling a superclass method

More documentation:

Python subclass inheritance of superclass constructors


Class attributes and methods

Private attributes of a class

__private_attrs: Starting with two underscores, this declares the attribute private and cannot be used or directly accessed outside the class. When used within a method within a class, use self.__private_attrs.

Class Methods

Within a class, use the def keyword to define a method. Unlike regular function definitions, class methods must include the parameter self as the first parameter. self represents the class instance.

The name of self is not fixed; you can also use this, but it is best to use self by convention.

Private Methods of a Class

__private_method: Starting with two underscores, this declares the method private and can only be called from within the class. self.__private_methods

Example

An example of a class’s private attributes is as follows:

Example (Python 3.0+)

#!/usr/bin/python3

class JustCounter:
__secretCount = 0 # Private variable
publicCount = 0 # Public variable

def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # Error: Instances cannot access private variables.

The output of executing the above program is:

1
2
2
Traceback (most recent call last):
File "test.py", line 16, in <module>
print (counter.__secretCount) # Error: Instance cannot access private variables
AttributeError: 'JustCounter' object has no attribute '__secretCount'

Class private method examples are as follows:

Example (Python 3.0+)

#!/usr/bin/python3

class Site:
def __init__(self, name, url):
self.name = name # public
self.__url = url # private

def who(self):
print('name : ', self.name)
print('url : ', self.__url)

def __foo(self): # Private method
print('This is a private method')

def foo(self): # Public method
print('This is a public method')
self.__foo()

x = Site('Geek Tutorial', 'www.geek-docs.com')
x.who() # Normal output
x.foo() # Normal output
x.__foo() # Error message

Class-specific methods:

  • __init__: Constructor, called when creating an object
  • __del__: Destructor, used when releasing an object
  • __repr__: Printing, conversion
  • __setitem__: Assign a value by index
  • __getitem__: Get a value by index
  • __len__: Get the length
  • __cmp__: Comparison operation
  • __call__: Function call
  • __add__: Addition
  • __sub__: Subtraction
  • __mul__: Multiplication
  • __truediv__: Division
  • __mod__: Modulus
  • __pow__: Exponentiation

Operator Overloading

Python also supports operator overloading. We can overload class-specific methods. An example is as follows:

Example (Python 3.0+)

#!/usr/bin/python3

class Vector:
def __init__(self, a, b):
      self.a = a
      self.b = b
 
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
 
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

The execution result of the above code is as follows:

Vector(7,8)

Leave a Reply

Your email address will not be published. Required fields are marked *