Home Backend Development Python Tutorial Python object-oriented advanced chapter

Python object-oriented advanced chapter

Aug 18, 2017 pm 01:34 PM
python Advanced For

The following editor will bring you an article about python advanced_a brief talk about object-oriented advancement. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

I learned the three major features of object-oriented inheritance, polymorphism, and encapsulation. Today we look at some advanced content of object-oriented, reflection and some built-in functions of classes.

1. isinstance and issubclass


##

class Foo:
 pass

class Son(Foo):
 pass

s = Son()
#判断一个对象是不是这个类的对象,传两个参数(对象,类)
print(isinstance(s,Son))
print(isinstance(s,Foo))
#type更精准
print(type(s) is Son)
print(type(s) is Foo)

#判断一个类是不是另一类的子类,传两个参数(子类,父类)
print(issubclass(Son,Foo))
print(issubclass(Son,object))
print(issubclass(Foo,object))
print(issubclass(int,object))
Copy after login

2. Reflection

The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect and modify its own state or behavior (introspection). The introduction of this concept quickly triggered research on applied reflectivity in the field of computer science. It was first adopted in the field of programming language design, and has achieved results in Lisp and object-oriented.

Reflection in python object-oriented: Manipulate object-related attributes in the form of strings. Everything in python is an object (reflection can be used)

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

The following methods are applicable Regarding classes and objects (everything is an object, the class itself is also an object)



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

 def func(self):
  print(123)

egg = Foo()
#常用:
#hasattr
#getattr
# print(hasattr(egg,'name'))
print(getattr(egg,'name'))
if hasattr(egg,'func'): #返回bool
 Foo_func = getattr(egg,'func') #如果存在这个方法或者属性,就返回属性值或者方法的内存地址
         #如果不存在,报错,因此要配合hasattr使用
 Foo_func()
#不常用:
#setattr
# setattr(egg,'sex','属性值')
# print(egg.sex)
# def show_name(self):
#  print(self.name + ' sb')
# setattr(egg,'sh_name',show_name)
# egg.sh_name(egg)
# show_name(egg)
# egg.sh_name()

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


# print(egg.name)
# egg.func()
# print(egg.__dict__)


#反射
#可以用字符串的方式去访问对象的属性、调用对象的方法
反射举例1
Copy after login


class Foo:
 f = 123 #类变量
 @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()
#类也是对象
Copy after login

Reflection example 2


import my_module
# print(hasattr(my_module,'test'))
# # func_test = getattr(my_module,'test')
# # func_test()
# getattr(my_module,'test')()
#import其他模块应用反射

from my_module import test


def demo1():
 print('demo1')

import sys
print(__name__) #'__main__'
print(sys.modules)
#&#39;__main__&#39;: <module &#39;__main__&#39; from &#39;D:/Python代码文件存放目录/S6/day26/6反射3.py&#39;>
module_obj =sys.modules[__name__] #sys.modules[&#39;__main__&#39;]
# module_obj : <module &#39;__main__&#39; from &#39;D:/Python代码文件存放目录/S6/day26/6反射3.py&#39;>
print(module_obj)
print(hasattr(module_obj,&#39;demo1&#39;))
getattr(module_obj,&#39;demo1&#39;)()
#在本模块中应用反射
反射举例3
Copy after login


#对象
#类
#模块 : 本模块和导入的模块

def register():
 print(&#39;register&#39;)

def login():
 pass

def show_shoppinglst():
 pass
#
print(&#39;注册,登录&#39;)
ret = input(&#39;欢迎,请输入您要做的操作: &#39;)
import sys
print(sys.modules)
# my_module = sys.modules[__name__]
# if hasattr(my_module,ret):
#  getattr(my_module,ret)()
if ret == &#39;注册&#39;:
 register()
elif ret == &#39;登录&#39;:
 login()
elif ret == &#39;shopping&#39;:
 show_shoppinglst()
反射举例4
Copy after login


def test():
 print(&#39;test&#39;)
Copy after login

3. Class built-in functions

1, __str__ and __repr__


class Foo:
 def __init__(self,name):
  self.name = name
 def __str__(self):
  return &#39;%s obj info in str&#39;%self.name
 def __repr__(self):
  return &#39;obj info in repr&#39;

f = Foo(&#39;egon&#39;)
# print(f)
print(&#39;%s&#39;%f)
print(&#39;%r&#39;%f)
print(repr(f)) # f.__repr__()
print(str(f))
#当打印一个对象的时候,如果实现了str,打印中的返回值
#当str没有被实现的时候,就会调用repr方法
#但是当你用字符串格式化的时候 %s和%r会分别去调用__str__和__repr__
#不管是在字符串格式化的时候还是在打印对象的时候,repr方法都可以作为str方法的替补
#但反之不行
#用于友好的表示对象。如果str和repr方法你只能实现一个:先实现repr
Copy after login

2, __del__


class Foo:
 def __del__(self):
  print(&#39;执行我啦&#39;)

f = Foo()
print(123)
print(123)
print(123)
#析构方法,当对象在内存中被释放时,自动触发执行。
#注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
Copy after login

3. item series

__getitem__\__setitem__\__delitem__


class Foo:
 def __init__(self):
  self.name = &#39;egon&#39;
  self.age = 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[&#39;name&#39;])
print(f[&#39;age&#39;])
f[&#39;name&#39;] = &#39;alex&#39;
# del f[&#39;name&#39;]
print(f.name)
f1 = Foo()
print(f == f1)
Copy after login

4, __new__


# class A:
#  def __init__(self): #有一个方法在帮你创造self
#   print(&#39;in init function&#39;)
#   self.x = 1
#
#  def __new__(cls, *args, **kwargs):
#   print(&#39;in new function&#39;)
#   return object.__new__(A, *args, **kwargs)
# a = A()
# b = A()
# c = A()
# d = A()
# print(a,b,c,d)

#单例模式
class Singleton:
 def __new__(cls, *args, **kw):
  if not hasattr(cls, &#39;_instance&#39;):
   cls._instance = object.__new__(cls, *args, **kw)
  return cls._instance

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

one.name = &#39;alex&#39;
print(two.name)
Copy after login

5, __call__


class Foo:
 def __init__(self):
  pass
 def __call__(self, *args, **kwargs):
  print(&#39;__call__&#39;)

obj = Foo() # 执行 __init__
obj() # 执行 __call__
Foo()() # 执行 __init__和执行 __call__
#构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
Copy after login

6, __len__, __hash__


class Foo:
 def __len__(self):
  return len(self.__dict__)
 def __hash__(self):
  print(&#39;my hash func&#39;)
  return hash(self.name)
f = Foo()
print(len(f))
f.name = &#39;egon&#39;
print(len(f))
print(hash(f))
Copy after login

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

#__eq__控制着==的结果
Copy after login

8. Built-in function examples


class FranchDeck:
 ranks = [str(n) for n in range(2,11)] + list(&#39;JQKA&#39;)
 suits = [&#39;红心&#39;,&#39;方板&#39;,&#39;梅花&#39;,&#39;黑桃&#39;]

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

纸牌游戏
Copy after login


class FranchDeck:
 ranks = [str(n) for n in range(2,11)] + list(&#39;JQKA&#39;)
 suits = [&#39;红心&#39;,&#39;方板&#39;,&#39;梅花&#39;,&#39;黑桃&#39;]

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

纸牌游戏2
Copy after login


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 other.sex == other.sex:return True


p_lst = []
for i in range(84):
 p_lst.append(Person(&#39;egon&#39;,i,&#39;male&#39;))

print(p_lst)
print(set(p_lst))

#只要姓名和年龄相同就默认为一人去重
Copy after login

The above is the detailed content of Python object-oriented advanced chapter. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles