Python 3 object oriented

Class object

Class objects support two operations: attribute reference and instantiation.
Attribute references use the same standard syntax as all attribute references in Python: obj name.
After a class object is created, all names in the class namespace are valid attribute names. So if the class definition is as follows:
The syntax format is as follows:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
class MyClass:
    """A simple class instance"""
    i = 12345
    def f(self):
        return 'hello world'
 
# Instantiation class
x = MyClass()
 
# Access the properties and methods of the class
print("MyClass Properties of class i Is:", x.i)
print("MyClass Class method f Output is:", x.f())
The above creates a new class instance and assigns the object to a local variable x,x Empty object.

After executing the above procedure, the output result is:

MyClass Properties of class i Is: 12345
MyClass Class method f Output is: hello world

Class has a name__ init__ (), which will be called automatically when the class is instantiated, as follows:

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

Class defines__ init__ () method, and the instantiation operation of the class will be called automatically__ init__ () method. Instantiate the class MyClass as follows, corresponding to__ init__ () method will be called:

x = MyClass()

Of course__ init__ () the method can have parameters, which can be passed__ init__ () passed to the instantiation operation of the class. For example:

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 result: 3.0 - 4.5

self represents an instance of a class, not a class
Class methods are only different from ordinary functions -- they must have an additional first parameter name, which is conventionally 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

It is obvious from the execution results that self represents the instance of the class and the address of the current object, while self Class points to the class.

self is not a python keyword. It can be executed normally if we replace it with runoob:

class Test:
    def prt(runoob):
        print(runoob)
        print(runoob.__class__)
 
t = Test()
t.prt()
The execution result of the above example is:

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

Class method

Inside the class, use the def keyword to define a method. Different from the general function definition, the class method must contain the parameter self, which is the first parameter. Self represents the instance of the class.

#Class definition
class people:
    #Define basic properties
    name = ''
    age = 0
    #Define private properties, which cannot be accessed directly outside the class
    __weight = 0
    #Define construction method
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say: I %d Years old." %(self.name,self.age))
 
# Instantiation class
p = people('runoob',10,30)
p.speak()
After executing the above procedure, the output result is:

runoob say: I'm 10 years old.

inherit

Python also has limited support for multiple inheritance forms. The class definition of multiple inheritance is as follows:

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

The subclass (derived class DerivedClassName) inherits the properties and methods of the parent class (base class BaseClassName).

BaseClassName (the base class name in the instance) 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):
class people:
    #Define basic properties
    name = ''
    age = 0
    #Define private properties, which cannot be accessed directly outside the class
    __weight = 0
    #Define construction method
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say: I %d Years old." %(self.name,self.age))
 
#Single inheritance example
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #Call the constructor of the parent class
        people.__init__(self,n,a,w)
        self.grade = g
    #Override method of parent class
    def speak(self):
        print("%s say: I %d Years old, I'm reading %d grade"%(self.name,self.age,self.grade))
 
s = student('ken',10,60,3)
s.speak()
After executing the above procedure, the output result is:

ken say: I'm 10 years old. I'm in grade 3

Multiple inheritance

Python also has limited support for multiple inheritance forms. The class definition of multiple inheritance is as follows:

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

Note the order of parent classes in parentheses. If the parent class has the same method name and is not specified when the child class is used, python searches from left to right, that is, if the method is not found in the child class, it searches from left to right whether the parent class contains the method.

#Class definition
class people:
    #Define basic properties
    name = ''
    age = 0
    #Define private properties, which cannot be accessed directly outside the class
    __weight = 0
    #Define construction method
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say: I %d Years old." %(self.name,self.age))
 
#Single inheritance example
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #Call the constructor of the parent class
        people.__init__(self,n,a,w)
        self.grade = g
    #Override method of parent class
    def speak(self):
        print("%s say: I %d Years old, I'm reading %d grade"%(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. The theme 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()   #The method name is the same. By default, it calls the method of the parent class in front of the parameter position in parentheses


After executing the above procedure, the output result is:

My name is Tim,I am a speaker. The theme of my speech is Python

Class properties and methods

Private properties of class
__ private_attrs: it starts with two underscores and declares that the attribute is private and cannot be used or accessed directly outside the class. When used in methods inside a class, self__ private_attrs.

Class method
Inside the class, use the def keyword to define a method. Different from the general function definition, the class method must contain the parameter self, which is the first parameter. Self represents the instance of the class.

The name of self is not specified. You can also use this, but it's best to use self according to the Convention.

Private method of class
__ private_method: it starts with two underscores and declares that the method is private. It can only be called inside the class, not outside the class. self.__private_methods.

example
Examples of private properties of class are as follows:

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)  # An error is reported. The instance cannot access private variables
 After executing the above procedure, the output result is:



Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print (counter.__secretCount)  # An error is reported. The instance cannot access private variables
AttributeError: 'JustCounter' object has no attribute '__secretCount'

Examples of private methods of class are as follows:

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('ha-ha', 'www.runoob.com')
x.who()        # Normal output
x.foo()        # Normal output
x.__foo()      # report errors


Class specific methods:
__ init__ : Constructor, called when the object is generated
__ del__ : Destructor, used when releasing an object
__ repr__ : Printing, converting
__ setitem__ : Assignment by index
__ getitem__: Get value by index
__ len__: Get length
__ cmp__: Comparison operation
__ call__: function call
__ add__: Addition operation
__ sub__: Subtraction operation
__ mul__: Multiplication operation
__ truediv__: Division operation
__ mod__: Remainder operation
__ pow__: Power

Operator overloading

Python also supports operator overloading. We can overload special methods of classes. Examples are as follows:

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 results of the above code are as follows:

Vector(7,8)

Keywords: Python

Added by siri_suresh on Sun, 09 Jan 2022 09:43:05 +0200