Python implements an example of adding properties and methods dynamically

  • 2020-11-20 06:09:25
  • OfStack

This article illustrates Python's implementation of dynamically adding properties and method operations. To share for your reference, the details are as follows:


# -*- coding:utf-8 -*-
#!python3
class Person():
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person('ff', '28')
print(p1.name, p1.age)
#  Add an instance object dynamically sex attribute 
p1.sex = 'female'
print(p1.sex)
#  Add properties to a class dynamically 
Person.height = None
print(Person.height)
p1.height = '155'
print(p1.height)
#  Dynamic definition 1 A method of 
def run(self, speed):
  print('run with %d speed' % speed)
#  Bind a method to an instance 
import types
p1.run = types.MethodType(run, p1)
p1.run(30)
# Person.run = run #  Runtime error 
# Person.run(4)
@classmethod
def run2(a, speed):
  print('run with %d m/s' % speed)
#  Give a class dynamic binding method 
Person.run2 = run2    #  A method to bind to a class needs a modifier @classmethod,  Label them as class methods that can be added by a class 
Person.run2(4)
p1.run2(5)       #  An instance object of a class can also call methods that the class adds dynamically 
@staticmethod
def eat():
  print('eat---')
Person.eat = eat    #  Class can add static methods. When you define static methods, you need to add modifiers @staticmethod
Person.eat()
p1.eat()        #  Instance objects can also call static methods dynamically added by classes 
del p1.name       # del  Delete the properties 
delattr(p1, 'sex')
print(p1.name, p1.sex)

Operation results:

[

ff 28
female
None
155
run with 30 speed
run with 4 m/s
run with 5 m/s
eat---
eat---
Traceback (most recent call last):
File "/ home python/Desktop test / 12 _ dynamic languages. py", line 41, in < module >
print(p1.name, p1.sex)
AttributeError: 'Person' object has no attribute 'name'

]

More about Python related content interested readers to view this site project: introduction to Python object-oriented programming and advanced tutorial ", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python coding skills summary" and "introduction to Python and advanced tutorial"

I hope this article has helped you with Python programming.


Related articles: