Home > Backend Development > Python Tutorial > Dynamically add methods to python class objects and instance objects

Dynamically add methods to python class objects and instance objects

小云云
Release: 2018-01-03 10:31:03
Original
1925 people have browsed it

This article mainly shares with you a method for dynamically adding python class objects and instance objects. It has great reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

The example is as follows:

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

def print_name(self):
 print(self.name)
p = Person('Li')
import types
p.print_name = types.MethodType(print_name, p) # 绑定函数到对象
p.print_name()

@staticmethod
def print_abc():
 print('abc')
Person.print_abc = print_abc
Person.print_abc()

@classmethod
def print_123(cls):
 print('123')
Person.print_123 = print_123
Person.print_123()
Copy after login

Related recommendations:

How to dynamically add styles to the HTML tags returned by Ajax

Using jQuery to dynamically add small ads Detailed explanation

Example Detailed explanation jQuery to realize simple dynamic addition and deletion of tables function

The above is the detailed content of Dynamically add methods to python class objects and instance objects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template