首页 > 其他 > 详细

面向对象编程——类方法和静态方法(八)

时间:2017-11-26 10:50:05      阅读:235      评论:0      收藏:0      [点我收藏+]

许多时候,我们创建了一个类,也定义了部分方法,如果我们想调用类中的方法,就必须创建一个对象,有时候显得非常的不方便。

python提供了classmethed(类方法)和staticmethed(静态方法)来解决这种情况。

普通方法绑定到对象,类方法绑定到类。

#使用一个方法一般要这样
class Classmethod_Demo():
    role = dog

    def func(self):
        print(‘123‘)

c = Classmethod_Demo()     #创建一个对象
c.func()    

使用classmethed和staticmethed也能达到这种效果。

classmethod(类方法):不需要实例化,直接用类名调用就好,不用接受self参数,默认传cls,cls代表当前所在的类。

staticmethod(静态方法):完全可以当作普通函数去用,只不过这个函数通过类名.函数名调用。其它的和一般的函数没有区别。

普通对象方法至少需要一个self参数,代表类对象实例。

class Classmethod_Demo():
    role = dog

    @classmethod       #类方法
    def func(cls):
        print("123")

Classmethod_Demo.func()

class staticmethod_Demo():
    role = "dog"

    @staticmethod      #静态方法
    def func():
        print("123")
staticmethod_Demo.func()

 

面向对象编程——类方法和静态方法(八)

原文:http://www.cnblogs.com/yangmingxianshen/p/7880198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!