SoFunction
Updated on 2024-11-14

Python Advanced_Object-Oriented Advanced

We've learned about the three main characteristics of object orientation: inheritance, polymorphism, and encapsulation. Today we will look at some advanced object-oriented content, reflection and some of the class built-in functions.

i. isinstance and issubclass

class Foo:
 pass

class Son(Foo):
 pass

s = Son()
# Determine if an object is an object of this class, passing two parameters (object, class).
print(isinstance(s,Son))
print(isinstance(s,Foo))
#type is more precise
print(type(s) is Son)
print(type(s) is Foo)

# Determine if a class is a subclass of another class, pass two arguments (subclass, parent)
print(issubclass(Son,Foo))
print(issubclass(Son,object))
print(issubclass(Foo,object))
print(issubclass(int,object))

II. Reflections

The concept of reflexivity was first introduced by Smith in 1982 and focuses on an ability of a program to access, detect and modify its own state or behavior (introspection). The introduction of this concept soon triggered research on applied reflexivity in computer science. It was first adopted by the field of programming language design, with achievements in Lisp and object orientation.

Reflection in python object-oriented:Manipulate object-related properties in the form of strings. everything in python is an object (all can use reflection)

Four functions that can implement reflection:hasattr,getattr,setattr,delattr

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

class Foo:
 def __init__(self):
   = 'egon'
   = 73

 def func(self):
  print(123)

egg = Foo()
#Common use:
#hasattr
#getattr
# print(hasattr(egg,'name'))
print(getattr(egg,'name'))
if hasattr(egg,'func'): # Returns bool
 Foo_func = getattr(egg,'func') # If the method or attribute exists, return the attribute value or the memory address of the method.
         # Report an error if it doesn't exist, so use it with hasattr.
 Foo_func()
#Not often used:
#setattr
# setattr(egg,'sex','attribute value')
# print()
# def show_name(self):
#  print( + ' sb')
# setattr(egg,'sh_name',show_name)
# egg.sh_name(egg)
# show_name(egg)
# egg.sh_name()

#delattr
# delattr(egg,'name')
# print()


# print()
# ()
# print(egg.__dict__)


# Reflections
# You can access an object's properties and call an object's methods as a string.
Reflection example1
class Foo:
 f = 123 # Class variables
 @classmethod
 def class_method_demo(cls):
  print('class_method_demo')
 @staticmethod
 def static_method_demo():
  print('static_method_demo')
# if hasattr(Foo,'f'):
#  print(getattr(Foo,'f'))
print(hasattr(Foo,'class_method_demo'))
method = getattr(Foo,'class_method_demo')
method()
print(hasattr(Foo,'static_method_demo'))
method2 = getattr(Foo,'static_method_demo')
method2()
# Classes are also objects
Reflection example 2
import my_module
# print(hasattr(my_module,'test'))
# # func_test = getattr(my_module,'test')
# # func_test()
# getattr(my_module,'test')()
#import other modules to apply reflection

from my_module import test


def demo1():
 print('demo1')

import sys
print(__name__) #'__main__'
print()
#'__main__': <module '__main__' from 'D:/Python code file repository directory/S6/day26/6reflections'>
module_obj =[__name__] #['__main__']
# module_obj : <module '__main__' from 'D:/Python code file repository directory/S6/day26/6reflections' >
print(module_obj)
print(hasattr(module_obj,'demo1'))
getattr(module_obj,'demo1')()
# Apply reflection in this module
Reflection example3
#Objects
# Class
# Modules: this module and imported modules

def register():
 print('register')

def login():
 pass

def show_shoppinglst():
 pass
#
print('Register, Login')
ret = input('Welcome, please enter the action you want to do: ')
import sys
print()
# my_module = [__name__]
# if hasattr(my_module,ret):
#  getattr(my_module,ret)()
if ret == 'Register':
 register()
elif ret == 'Login':
 login()
elif ret == 'shopping':
 show_shoppinglst()
Reflection example4
def test():
 print('test')

III. Built-in Functions of Classes

1. __str__ and __repr__

class Foo:
 def __init__(self,name):
   = name
 def __str__(self):
  return '%s obj info in str'%
 def __repr__(self):
  return 'obj info in repr'

f = Foo('egon')
# print(f)
print('%s'%f)
print('%r'%f)
print(repr(f)) # f.__repr__()
print(str(f))
# When printing an object, if str is implemented, the return value in the print
# The repr method is called when str is not implemented
# But when you format strings %s and %r go to __str__ and __repr__, respectively.
# The repr method can be used as a stand-in for the str method both when formatting strings and when printing objects
# But not the other way around
#For friendly representation of objects。in the event thatstrcap (a poem)reprmethod you can only implement one:first realizerepr

2、__del__

class Foo:
 def __del__(self):
  print("Execute me.)

f = Foo()
print(123)
print(123)
print(123)
# destructor method that is automatically triggered to execute when the object is freed in memory.
# Note: This method does not need to be defined, because Python is a high-level language, programmers do not need to care about the allocation and release of memory when using it, because this work is handed over to the Python interpreter to perform, so the destructor call is automatically triggered by the interpreter in the garbage collection execution.

3、item series

__getitem__\__setitem__\__delitem__

class Foo:
 def __init__(self):
   = 'egon'
   = 73
  
 def __getitem__(self, item):
  return self.__dict__[item]

 def __setitem__(self, key, value):
  # print(key,value)
  self.__dict__[key] = value

 def __delitem__(self, key):
  del self.__dict__[key]
f = Foo()
print(f['name'])
print(f['age'])
f['name'] = 'alex'
# del f['name']
print()
f1 = Foo()
print(f == f1)

4、__new__

# class A:
# def __init__(self): # There's a method that's helping you create self
#   print('in init function')
#    = 1
#
#  def __new__(cls, *args, **kwargs):
#   print('in new function')
#   return object.__new__(A, *args, **kwargs)
# a = A()
# b = A()
# c = A()
# d = A()
# print(a,b,c,d)

#Single instance pattern
class Singleton:
 def __new__(cls, *args, **kw):
  if not hasattr(cls, '_instance'):
   cls._instance = object.__new__(cls, *args, **kw)
  return cls._instance

one = Singleton()
two = Singleton()
three = Singleton()
go = Singleton()
print(one,two)

 = 'alex'
print()

5、__call__

class Foo:
 def __init__(self):
  pass
 def __call__(self, *args, **kwargs):
  print('__call__')

obj = Foo() # Execute __init__
obj() # Execute __call__
Foo()() # Executing __init__ and executing __call__
#The execution of a constructor method is triggered by the creation of an object,assume (office):boyfriend = class name() ;as for __call__ 方法的执行是由boyfriend后加括号触发的,assume (office):boyfriend() or resemble()()

6、__len__,__hash__

class Foo:
 def __len__(self):
  return len(self.__dict__)
 def __hash__(self):
  print('my hash func')
  return hash()
f = Foo()
print(len(f))
 = 'egon'
print(len(f))
print(hash(f))

7、__eq__

class A:
 def __init__(self):
   = 1
   = 2

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

#__eq__control==results

8. Examples of built-in functions

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

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

 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))

card game
class FranchDeck:
 ranks = [str(n) for n in range(2,11)] + list('JQKA')
 suits = ['Red Heart','Square plate','Plum Blossom','Spades']

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

 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])

card game2
class Person:
 def __init__(self,name,age,sex):
   = name
   = age
   = sex

 def __hash__(self):
  return hash(+)

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


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

print(p_lst)
print(set(p_lst))

# Defaults to one person de-duplication as long as the name and age are the same

de-emphasize

Above this python progression_An introduction to object-oriented progression is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.