PythonのDunderまたはmagicメソッド
オブジェクト指向プログラミングでかなり巧妙なトリックを実行できる魔法のメソッド。これらのメソッドは、プレフィックスとサフィックスとして使用される2つのアンダースコア(__)で識別されます。例として、特定の条件が満たされたときに自動的に呼び出されるインターセプターとして機能します。
Pythonでは、__ repr__はオブジェクトの「公式」文字列表現を計算するために使用される組み込み関数であり、__str__はオブジェクトの「非公式」文字列表現を計算する組み込み関数です。
サンプルコード
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# Driver Code
if __name__ == '__main__':
# object creation
my_string = String('Python')
# print object location
print(my_string)
出力
<__main__.String object at 0x000000BF0D411908>
サンプルコード
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
# Driver Code
if __name__ == '__main__':
# object creation
my_string = String('Python')
# print object location
print(my_string)
出力
Object: Python
文字列を追加しようとしています。
サンプルコード
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
# Driver Code
if __name__ == '__main__':
# object creation
my_string = String('Python')
# concatenate String object and a string
print(my_string + ' Program')
出力
TypeError: unsupported operand type(s) for +: 'String' and 'str'
ここで、__add__メソッドをStringクラスに追加します
サンプルコード
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
def __add__(self, other):
return self.string + other
# Driver Code
if __name__ == '__main__':
# object creation
my_string = String('Hello')
# concatenate String object and a string
print(my_string +' Python')
出力
Hello Python
-
Pythonでタイムスタンプ文字列を日時オブジェクトに変換する方法は?
datetimeモジュールのfromtimestamp関数を使用して、UNIXタイムスタンプから日付を取得できます。この関数は、タイムスタンプを入力として受け取り、タイムスタンプに対応する日時オブジェクトを返します。 例 import datetime timestamp = datetime.datetime.fromtimestamp(1500000000) print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) 出力 これにより、出力が得られます- 2017-07-14 08:10:00
-
Pythonの日付文字列を日付オブジェクトに変換するにはどうすればよいですか?
strptime関数を使用して、文字列を日付オブジェクトに変換できます。日付文字列と日付を指定する形式を指定します。 例 import datetime date_str = '29122017' # The date - 29 Dec 2017 format_str = '%d%m%Y' # The format datetime_obj = datetime.datetime.strptime(date_str, format_str) print(datetime_obj.date()) 出力 これにより、出力が得られます- 2017-12-29