181016 Python内置函数__getitem__,__str__,__repr__,__len__

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_33039859/article/details/83090870

Python内置函数

  • __getitem__: 定义该内置函数后,类的实例对象可以按列表方式返回元素。

  • __str__:
    1⃣️无__repr__的时候,command中的实例对象将返回内存地址,command 中print(instance)将会返会__str__中定义的字符串。
    2⃣️有__repr__的时候,command中的实例对象instance将返回__repr__中定义的字符串,command 中print(instance)将会返会__str__中定义的字符串。

  • __repr__: 同样可以返回预先定义的字符串,参见__str__

  • __len__: 定义后,可以调用python自带的len()函数,测量实例对象的长度。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2018/10/15

@author: brucelau
"""

import numpy as np
from torchvision.datasets import MNIST,CIFAR10
import torch

a = np.random.random((1000,2,2))

class Sample():
    '''
    if both __str__ and __repr__ are defined 
    
    instance in command will return __repr__ string.
    print(instance) in command will return __str__ string.
    '''
    def __init__(self,data):
        self.data = data
        print('Data Loaded.')

    def __getitem__(self, idx):
        return self.data[idx]
    def __str__(self):
        '''
        for users:
        if define: print(instance) will return the defined string,
        but the instance in command will only present the memory location.
        '''
        return 'This is str function'
    def __repr__(self):
        '''
        for programmers:
        if define: both print(instance) and instance in command will return the defined string.
        '''
        return 'This is repr test.'
    def __len__(self):
        return len(self.data)
s = Sample(a)

print(a[0] == s[0])

print('The instance length is %d.'%len(s))


#%%
m = MNIST(root='./data', train=True, download=True)
p = './data/processed/training.pt'
data1, label1 = torch.load(p)

#%%
m = CIFAR10(root='./data', train=True, download=True)
p = './data/processed/training.pt'
data2, label2 = torch.load(p)


猜你喜欢

转载自blog.csdn.net/qq_33039859/article/details/83090870