Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Magic Method

Back


Magic Method


__contains__()

class Method:

    # Calling the __init__ method and initializing the attributes
    def __init__(self, attribute):
        self.attribute = attribute

    # Calling the __contains__ method
    def __contains__(self, attribute):
        return attribute in self.attribute


# Creating an instance of the class
instance = Method([4, 6, 8, 9, 1, 6])

# Checking if a value is present in the container attribute
print("4 is contained in ""attribute"": ", 4 in instance)   # True
print("5 is contained in ""attribute"": ", 5 in instance)   # False

__iter__()

class Method:
    def __init__(self, start_value, stop_value):
        self.start = start_value
        self.stop = stop_value

    def __iter__(self):
        for num in range(self.start, self.stop + 1):
            yield num ** 2


# Creating an instance
instance = iter(Method(3, 8))
print(next(instance))       # 9
print(next(instance))       # 16
print(next(instance))       # 25
print(next(instance))       # 36
print(next(instance))       # 49
print(next(instance))       # 64

__setitem__() & __getitem__()

class record:

    def __init__(self):
        self.record = {}

    def __getitem__(self, key):
        if key in self.record:
            return self.record[key]
        else:
            return None

    def __setitem__(self, key, newvalue):
        self.record[key] = newvalue


rec = record()

rec['fname'] = 'John'
rec['lname'] = 'Wick'

print(rec['fname'])     # John
print(rec['lname'])     # Wick
print(rec['age'])       # None

__delitem__()

class record:

    def __init__(self, dict):
        self.dict = dict

    def __len__(self):
        return len(self.dict)

    def __setitem__(self, key, value):
        self.dict[key] = value

    def __getitem__(self, key):
        if key in self.dict:
            return self.dict[key]
        else:
            return None

    def __delitem__(self, key):
        if key in self.dict:
            del self.dict[key]


aList = {'fname': 'John'}
rec = record(aList)

print(len(rec))           # 1
print(rec['fname'])       # John

rec['fname'] = 'Winston'
rec['lname'] = 'Wick'
print(rec['fname'])       # Winston
print(rec['lname'])       # Wick

del rec['fname']
print(rec['fname'])       # None
print(rec['lname'])       # Wick

__len__()

class record:

    def __init__(self, arr):
        self.record = arr

    def __len__(self):
        return len(self.record)


aList = [0, 1, 2, 3, 4]
rec = record(aList)

print(len(rec))     # 5


Top