Python - Object Oriented Advancement

Keywords: Python Attribute encoding Programming

isinstance and issubclass

isinstance(obj,cls) checks if obj is an object of class CLS

class Foo(object):
     pass
  
obj = Foo()
  
isinstance(obj, Foo)

issubclass(sub, super) Checks if the subclass is a derived class of the super class

class Foo(object):
    pass
 
class Bar(Foo):
    pass
 
issubclass(Bar, Foo)

reflex

1 What is reflection

The concept of reflection, first introduced by Smith in 1982, refers primarily to the ability of a program to access, detect, and modify its own state or behavior (introspection).The introduction of this concept soon led to the study of application reflectivity in computer science.It was first adopted in the field of programming language design and has achieved results in Lisp and object-oriented.

Reflection in 2 python object-oriented: Operates object-related properties as strings.Everything in python is an object (reflection can be used)

Four functions for introspection

The following methods apply to classes and objects (everything is an object, and the class itself is an object)

 

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass
hasattr
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
getattr
def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass
setattr
def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
delattr
class Foo:
    f = 'Static variable of class'
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say_hi(self):
        print('hi,%s'%self.name)

obj=Foo('egon',73)

#Detect if an attribute exists
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))

#get attribute
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()

print(getattr(obj,'aaaaaaaa','Does not exist')) #Report errors

#set a property
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))

#Delete Properties
delattr(obj,'age')
delattr(obj,'show_name')
delattr(obj,'show_name111')#Non-existent,Error then

print(obj.__dict__)
Demonstration of the use of four methods

 

class Foo(object):
 
    staticField = "old boy"
 
    def __init__(self):
        self.name = 'wupeiqi'
 
    def func(self):
        return 'func'
 
    @staticmethod
    def bar():
        return 'bar'
 
print getattr(Foo, 'staticField')
print getattr(Foo, 'func')
print getattr(Foo, 'bar')
Classes are also objects

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys


def s1():
    print 's1'


def s2():
    print 's2'


this_module = sys.modules[__name__]

hasattr(this_module, 's1')
getattr(this_module, 's2')
Reflect current module members

Import other modules and use reflection to find out if a method exists for that module

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def test():
    print('from the test')

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
"""
//Program directory:
    module_test.py
    index.py
 
//Current file:
    index.py
"""

import module_test as obj

#obj.test()

print(hasattr(obj,'test'))

getattr(obj,'test')()

 

_u str_u and u repr_u

Changing the string display of an object u str_u, u repr_u

Custom Formatting String_u format_u

#_*_coding:utf-8_*_

format_dict={
    'nat':'{obj.name}-{obj.addr}-{obj.type}',#School Name-School Address-School type
    'tna':'{obj.type}:{obj.name}:{obj.addr}',#School type:School Name:School Address
    'tan':'{obj.type}/{obj.addr}/{obj.name}',#School type/School Address/School Name
}
class School:
    def __init__(self,name,addr,type):
        self.name=name
        self.addr=addr
        self.type=type

    def __repr__(self):
        return 'School(%s,%s)' %(self.name,self.addr)
    def __str__(self):
        return '(%s,%s)' %(self.name,self.addr)

    def __format__(self, format_spec):
        # if format_spec
        if not format_spec or format_spec not in format_dict:
            format_spec='nat'
        fmt=format_dict[format_spec]
        return fmt.format(obj=self)

s1=School('oldboy1','Beijing','private')
print('from repr: ',repr(s1))
print('from str: ',str(s1))
print(s1)

'''
str Function or print function--->obj.__str__()
repr Or an interactive interpreter--->obj.__repr__()
//If u str_ is not defined, then u repr_ will be used instead of output
//Note: Both methods must return a string or throw an exception
'''
print(format(s1,'nat'))
print(format(s1,'tna'))
print(format(s1,'tan'))
print(format(s1,'asfdasdffd'))
class B:

     def __str__(self):
         return 'str : class B'

     def __repr__(self):
         return 'repr : class B'


b=B()
print('%s'%b)
print('%r'%b)
%s and%r

item series

__getitem__\__setitem__\__delitem__

class Foo:
    def __init__(self,name):
        self.name=name

    def __getitem__(self, item):
        print(self.__dict__[item])

    def __setitem__(self, key, value):
        self.__dict__[key]=value
    def __delitem__(self, key):
        print('del obj[key]time,I Execute')
        self.__dict__.pop(key)
    def __delattr__(self, item):
        print('del obj.key time,I Execute')
        self.__dict__.pop(item)

f1=Foo('sb')
f1['age']=18
f1['age1']=19
del f1.age1
del f1['age']
f1['name']='alex'
print(f1.__dict__)

__del__

A destructor that automatically triggers execution when an object is released in memory.

Note: This method generally does not need to be defined because Python is a high-level language and programmers do not need to be concerned with memory allocation and release when using it, since this work is left to the Python interpreter to perform, so calls to destructors are triggered automatically by the interpreter when garbage collection occurs.

class Foo:

    def __del__(self):
        print('Execute me')

f1=Foo()
del f1
print('------->')

#Output Results
Execute me
------->
Simple demonstration

__new__

class A:
    def __init__(self):
        self.x = 1
        print('in init function')
    def __new__(cls, *args, **kwargs):
        print('in new function')
        return object.__new__(A)

a = A()
print(a.x)
class Singleton:
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls)
        return cls._instance

one = Singleton()
two = Singleton()

two.a = 3
print(one.a)
# 3
# one and two Exactly the same,Can be used id(), ==, is Testing
print(id(one))
# 29097904
print(id(two))
# 29097904
print(one == two)
# True
print(one is two)
Singleton mode

__call__

Enclose the object with parentheses to trigger execution.

Note: The execution of the construction method is triggered by the creation of the object, that is, object = class name (); and the execution of the u call_u method is triggered by parentheses after the object, that is, object () or class ()).

class Foo:

    def __init__(self):
        pass
    
    def __call__(self, *args, **kwargs):

        print('__call__')


obj = Foo() # implement __init__
obj()       # implement __call__

with and u enter_u, u exit_u

class A:
    def __enter__(self):
        print('before')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('after')


with A() as a:
    print('123')
with statement
class A:
    def __init__(self):
        print('init')
        
    def __enter__(self):
        print('before')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('after')


with A() as a:
    print('123')
with statement and init
class Myfile:
    def __init__(self,path,mode='r',encoding = 'utf-8'):
        self.path = path
        self.mode = mode
        self.encoding = encoding

    def __enter__(self):
        self.f = open(self.path, mode=self.mode, encoding=self.encoding)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()


with Myfile('file',mode='w') as f:
    f.write('wahaha')
with and file operations
import  pickle
class MyPickledump:
    def __init__(self,path):
        self.path = path

    def __enter__(self):
        self.f = open(self.path, mode='ab')
        return self

    def dump(self,content):
        pickle.dump(content,self.f)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

class Mypickleload:
    def __init__(self,path):
        self.path = path

    def __enter__(self):
        self.f = open(self.path, mode='rb')
        return self


    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    def load(self):
         return pickle.load(self.f)


    def loaditer(self):
        while True:
            try:
                yield  self.load()
            except EOFError:
                break



# with MyPickledump('file') as f:
#      f.dump({1,2,3,4})

with Mypickleload('file') as f:
    for item in f.loaditer():
        print(item)
with and pickle
import  pickle
class MyPickledump:
    def __init__(self,path):
        self.path = path

    def __enter__(self):
        self.f = open(self.path, mode='ab')
        return self

    def dump(self,content):
        pickle.dump(content,self.f)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

class Mypickleload:
    def __init__(self,path):
        self.path = path

    def __enter__(self):
        self.f = open(self.path, mode='rb')
        return self


    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    def __iter__(self):
        while True:
            try:
                yield  pickle.load(self.f)
            except EOFError:
                break



# with MyPickledump('file') as f:
#      f.dump({1,2,3,4})

with Mypickleload('file') as f:
    for item in f:
        print(item)
with and pickle and iter

__len__

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __len__(self):
        return len(self.__dict__)
a = A()
print(len(a))

__hash__

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __hash__(self):
        return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))

__eq__

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __eq__(self,obj):
        if  self.a == obj.a and self.b == obj.b:
            return True
a = A()
b = A()
print(a == b)

 

class FranchDeck:
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = ['Red heart','Square board','Plum Blossom','Spade']

    def __init__(self):
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]

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

    def __getitem__(self, item):
        return self._cards[item]

deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))
Solitaire Game 1
class FranchDeck:
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = ['Red heart','Square board','Plum Blossom','Spade']

    def __init__(self):
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]

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

    def __getitem__(self, item):
        return self._cards[item]

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

deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))

from random import shuffle
shuffle(deck)
print(deck[:5])
Solitaire Game 2
class Person:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def __hash__(self):
        return hash(self.name+self.sex)

    def __eq__(self, other):
        if self.name == other.name and self.sex == other.sex:return True


p_lst = []
for i in range(84):
    p_lst.append(Person('egon',i,'male'))

print(p_lst)
print(set(p_lst))
An interview question

Posted by m!tCh on Sat, 15 Feb 2020 11:46:35 -0800