python 高级编程:类方法、实例方法、静态方法的定义个区别

python 高级编程

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

import types

# 定义一个类
class Person(object):
    num = 0
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def eat_fun(self):
        print("eat food")

# 定义一个实例方法
def run(self,speed):
    print("%s在跑,速度是%d"%(self.name,speed))
@classmethod
def testClass(cls):
    cls.num =20

@staticmethod
def teststaticmethod():
    print("__static method__")

p = Person("lao wang",24)
# 调用在class方法
p.eat_fun()

# 添加实例方法
p.run = types.MethodType(run,p)
p.run(190)

# 类添加类方法
Person.testClass = testClass
print(Person.num)
Person.testClass()
print(Person.num)

# 类绑定静态方法
Person.teststaticmethod = teststaticmethod
Person.teststaticmethod()
p.del(age)

解析

  • 概念区分:类、类属性、实例属性、实例方法、类方法、静态方法
  • 区别:类属性和实例属性区别
    • 类属性是描述类的性质
    • 实例属性是描述实例的特性
  • 类方法和实例方法
    • 类方法可以改变类属性的函数
      • 类方法
      • 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); 调用:实例对象和类对象都可以调用。
    • 实例方法是实例的功能
      • 实例方法
        • 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法);调用:只能由实例对象调用。
    • 静态方法
      • 静态方法 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; 调用:实例对象和类对象都可以调用
发布了299 篇原创文章 · 获赞 129 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_32393347/article/details/103035862