Pythonオブジェクト向けプログラミング——バインド方法と非バインド方法
2714 ワード
Pythonオブジェクト向けプログラミング——バインド方法と非バインド方法
一、クラスで定義された関数は二大クラスに分けられる
1、バインド方法(誰にバインドするか、誰が呼び出すかは自動的にそれ自体を最初のパラメータとして入力する
1)クラスにバインドする方法:classmethodアクセサリーで飾る方法.
2)オブジェクトにバインドする方法:どんな装飾器にも装飾されていない方法.
2、非バインド方法:staticmethod装飾器で装飾する方法
クラスやオブジェクトにバインドされず、クラスもオブジェクトも呼び出すことができますが、自動伝値はありません.普通の道具です
注意:オブジェクトにバインドされたメソッドとは区別され、クラスで直接定義された関数は、どんな装飾器にも装飾されていないもので、オブジェクトにバインドされたメソッドですが、普通の関数ではありません.オブジェクトがこのメソッドを呼び出すと自動的に値が伝わりますが、staticmethod装飾のメソッドは、誰が調整しても、自動的に値が伝わりません.
二、バインド方法
オブジェクトにバインドする方法(略)
クラスにバインドする方法(classmethod):
classmehtodはクラス用、すなわちクラスにバインドされ、クラスは使用時にクラス自体をパラメータとしてクラスメソッドの最初のパラメータに伝達します(オブジェクトが呼び出されてもクラスを最初のパラメータとして伝達します)、pythonはクラス内の関数classmethodを内蔵してクラスメソッドに定義します
三、非バインド方法
クラス内部にstaticmethodで装飾された関数である非バインドメソッドは,通常の関数である.
statimethodはクラスやオブジェクトにバインドされず、誰でも呼び出すことができ、自動値伝達効果はありません.
四、classmethodとstaticmethodの対比
一、クラスで定義された関数は二大クラスに分けられる
1、バインド方法(誰にバインドするか、誰が呼び出すかは自動的にそれ自体を最初のパラメータとして入力する
1)クラスにバインドする方法:classmethodアクセサリーで飾る方法.
.boud_method(),
( , )
2)オブジェクトにバインドする方法:どんな装飾器にも装飾されていない方法.
.boud_method(),
( , , , )
2、非バインド方法:staticmethod装飾器で装飾する方法
クラスやオブジェクトにバインドされず、クラスもオブジェクトも呼び出すことができますが、自動伝値はありません.普通の道具です
注意:オブジェクトにバインドされたメソッドとは区別され、クラスで直接定義された関数は、どんな装飾器にも装飾されていないもので、オブジェクトにバインドされたメソッドですが、普通の関数ではありません.オブジェクトがこのメソッドを呼び出すと自動的に値が伝わりますが、staticmethod装飾のメソッドは、誰が調整しても、自動的に値が伝わりません.
二、バインド方法
オブジェクトにバインドする方法(略)
クラスにバインドする方法(classmethod):
classmehtodはクラス用、すなわちクラスにバインドされ、クラスは使用時にクラス自体をパラメータとしてクラスメソッドの最初のパラメータに伝達します(オブジェクトが呼び出されてもクラスを最初のパラメータとして伝達します)、pythonはクラス内の関数classmethodを内蔵してクラスメソッドに定義します
#settings.py
HOST='127.0.0.1'
PORT=3306
DB_PATH=r'C:\Users\Administrator\PycharmProjects\test\ \test1\db'
#test.py
import settings
class MySQL:
def __init__(self,host,port):
self.host=host
self.port=port
@classmethod
def from_conf(cls):
print(cls)
return cls(settings.HOST,settings.PORT)
print(MySQL.from_conf) #>
conn=MySQL.from_conf()
conn.from_conf() # ,
三、非バインド方法
クラス内部にstaticmethodで装飾された関数である非バインドメソッドは,通常の関数である.
statimethodはクラスやオブジェクトにバインドされず、誰でも呼び出すことができ、自動値伝達効果はありません.
import hashlib
import time
class MySQL:
def __init__(self,host,port):
self.id=self.create_id()
self.host=host
self.port=port
@staticmethod
def create_id(): #
m=hashlib.md5(str(time.time()).encode('utf-8'))
return m.hexdigest()
print(MySQL.create_id) # #
conn=MySQL('127.0.0.1',3306)
print(conn.create_id) # #
四、classmethodとstaticmethodの対比
class MySQL:
def __init__(self,host,port):
self.host=host
self.port=port
@staticmethod
def from_conf():
return MySQL(settings.HOST,settings.PORT)
# @classmethod # ,
# def from_conf(cls):
# return cls(settings.HOST,settings.PORT)
def __str__(self):
return ' '
class Mariadb(MySQL):
def __str__(self):
return '' %(self.host,self.port)
m=Mariadb.from_conf()
print(m) # Mariadb.__str__, MySQL.__str__ , :