13、高度なオブジェクト指向

1.オブジェクトの継承

 クラスは、1つの親クラスまたは複数の親クラスを継承できます。その中で、前者は単一継承と呼ばれ、後者は多重継承と呼ばれます。

単一継承:クラスサブクラス名(親クラス)
多重継承:クラスサブクラス名(親クラス1、親クラス2、...)

例1:完全な継承

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
    def area(self):
        return self.length*self.width
        
class Square(Rectangle):
     pass
squ=Square(6,6)
print(squ.area())

実行結果:36

例2:部分的な継承、メソッドの変更なし

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
        
    def area(self):
        return self.length*self.width
        
class Square(Rectangle):
     def __init__(self,side):   #只对初始化方法进行修改
        self.length=side
        self.width=side
squ=Square(6)
print(squ.area())

実施結果:36


例3:メソッドを継承して追加する際の部分的な継承

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
        
    def area(self):
        return self.length*self.width
        
    @classmethod
    def features(cls):
        print('父类的类方法')
        
class Square(Rectangle):
    def __init__(self,side):
        self.length=side
        self.width=side
    @classmethod
    def features(cls):
        super().features()    # 继承父类的同名方法的代码
        print('子类的类方法')  # 补充
squ=Square(6)
squ.features()

結果:

父类的类方法
子类的类方法


例4:多重継承

class people:
    def __init__(self,n,a):   #构造方法
        self.name = n  
        self.__age = a       
    def speak(self,height):     #实例方法,其中height为实例属性
        print("%s 说: 我 %d 岁,身高 %d cm。" %(self.name,self.age,height))

class speaker():
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多重继承
class sample(speaker,people):
    def __init__(self,n,a,t):
        people.__init__(self,n,a)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,"Python")
test.speak()   #方法名同,默认调用的是在括号中排较前父类的方法

==>我叫 Tim,我是一个演说家,我演讲的主题是 Python

注:親クラスに同じメソッド名があり、サブクラスの使用時に指定されていない場合、Pythonは親クラスを左から右に検索します

2.静的メソッドとクラスメソッドを区別します。

メソッド1:type()メソッド、
静的メソッドは関数を返し、クラスメソッドはメソッドを返します

class people:           
    @classmethod  #声明下面是个类方法
    def f1(cls):
        print('这是类方法')

    @staticmethod  #声明下面是个静态方法
    def f2():
        print('这是静态方法')
        
print(type(people.f1))
print(type(people.f2))

結果:

<class 'method'>
<class 'function'>

方法2:inspect()関数
はinspect.ismethod()とinspect.isfunction()で判断できます

#追加代码
import inspect
print(inspect.ismethod(people.f1))
print(inspect.isfunction(people.f2))

結果:

True
True

3.プライベート属性、プライベートメソッド

  • プライベート属性:サブクラスで継承できない属性
  • プライベートメソッド:サブクラスで継承できないメソッド
  • 形式:属性/メソッドの前に「__」を追加すると、プライベートになります

①直接プライベートに電話する:

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')

a=A()
print(a.__name)  #调用私有属性
a.__f1()    #调用私有方法

実行結果:エラー

AttributeError: 'A' object has no attribute '__name'
AttributeError: 'A' object has no attribute '__f1'

概要:プライベートプロパティを直接呼び出すと、プライベートメソッドはエラーを報告します

②継承を通じてプライベートを呼び出す:

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')

class B(A):
    pass
b=B()
print(b.__name)
b.__f1()

実行結果:エラー

AttributeError: 'B' object has no attribute '__name'
AttributeError: 'B' object has no attribute '__f1'


③間接電話

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')
    def f2(self):
        print(self.__name)
        self.__f1()

a=A()
a.f2()

結果:

private
这是一个私有方法

4.オブジェクトクラス

すべてのクラスはオブジェクトのサブクラスです

class A:
    """A的注释"""
class B(object):
    """B的注释"""

print(A.__bases__)  #查看A的父类
print(A.__doc__)  #查看A的注释
print(A.__name__)  #查看A的类名
print(B.__bases__)
print(B.__doc__)

の結果

(<class 'object'>,)
A的注释
A
(<class 'object'>,)
B的注释

5.ポリモーフィズム

class A():
    def f1(self):
        print('A的f1')
class B():
    def f1(self):
        print('B的f1')
        
def f(obj):  
    obj.f1()

f(A())  
f(B())  

結果:

A的f1
B的f1

おすすめ

転載: blog.csdn.net/weixin_45128456/article/details/112188096