python-面向对象- 实例方法,类方法,静态方法, 类属性

名称定义方法权限调用方法
实例方法 第一个参数必须是示例,一般命名为self 可以访问实例的属性和方法,也可以访问类的实例和方法 一般通过示例调用,类也可以调用
类方法 使用装饰器@classmethod修饰,第一个参数必须是当前的类对象,一般命名为cls 可以访问类的实例和方法 类实例和类都可以调用
静态方法 使用装饰器@staticmethod修饰,参数随意,没有self和cls 不可以访问类和实例的属性和方法 实例对象和类对象都可以调用

1.实例

#coding=utf-8
class stu:
    school ="湘湖高中";
    def __init__(self,name,age):
        self.name=name;
        self.age=age;
    def play(self):
        print "{name}在play".format(name=self.name);
    @classmethod
    def getschool(cls):
        print "school是{school}".format(school=cls.school);
    @staticmethod
    def getstatic():
        print "this is staticmethod";
s=stu("jack",28);
#通过实例调用实例方法
s.play();
#通过类调用实例方法
stu.play(s);
#通过实例调用类方法
s.getschool();
#通过类调用类方法
stu.getschool();
#通过实例调用静态方法
s.getstatic();
#通过类调用静态方法
stu.getstatic();

运行结果:

jack在play
jack在play
school是湘湖高中
school是湘湖高中
this is staticmethod

 

posted @ 2022-11-29 15:49  家乐福的搬砖日常  阅读(22)  评论(0编辑  收藏  举报