Python普通方法、静态方法、类方法

开始

# -*-coding:utf-8-*-
# 普通方法,类方法,静态方法的区别

__metaclass__ = type


class Tst:
    name = 'tst'

    data = 'this is data'

    # 普通方法
    def normalMethod(self, name):
        print self.data, name

    # 类方法,可以访问类属性
    @classmethod
    def classMethod(cls, name):
        print cls.data, name

    # 静态方法,不可以访问类属性
    @staticmethod
    def staticMethod(name):
        print name
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

测试

  • 三种方法都可以通过实例来调用,但是静态方法和类方法无法访问实例属性,所以更改了tst.data仅对普通方法起了作用
tst = Tst()
tst.data = 'this is new'
tst.normalMethod('name')
tst.staticMethod('name')
tst.classMethod('name')

#结果
this is new name
name
this is data name
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

区别

  • 普通方法不能通过类名调用,但是静态方法和类方法是可以的
# error普通方法必须通过实例调用
# Tst.normalMethod('name')
Tst.classMethod('name')
Tst.staticMethod('name')

#结果
this is data name
name
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

总结

  • 普通方法,可以通过self访问实例属性
def normalMethod(self,data)
  
  
  • 1
  • 类方法,可以通过cls访问类属性
@classmethod
def classMethod(cls,data)
  
  
  • 1
  • 2
  • 静态方法,不可以访问,通过传值的方式
@staticmethod
def staticMethod(data)
  
  
  • 1
  • 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的方法静态方法是两种特殊型的方法,它们与普通实例方法不同。我可以为你解释一下它们的区别和用法。 1. 方法(class method): - 方法是绑定到而不是实例的方法。这意味着无论通过还是实例调用方法,它们都将访问和操作级别的属性。 - 方法使用装饰器`@classmethod`来标识,并且第一个参数通常被命名为`cls`,表示本身。 - 方法可以通过调用,也可以通过实例调用。当通过实例调用时,实际上会自动将实例转换为并传递给第一个参数`cls`。 2. 静态方法(static method): - 静态方法和实例都无关,它们与和实例的任何属性和方法都没有直接的关系。 - 静态方法使用装饰器`@staticmethod`来标识,它们没有隐含的第一个参数。 - 静态方法可以通过直接调用,也可以通过实例调用。与方法不同,静态方法无法访问的属性或调用其他方法。 下面是一个示例代码来说明它们的使用: ```python class MyClass: class_variable = "Hello, world!" @classmethod def class_method(cls): print("This is a class method") print("Class variable:", cls.class_variable) @staticmethod def static_method(): print("This is a static method") # 通过调用方法静态方法 MyClass.class_method() MyClass.static_method() # 通过实例调用方法静态方法 my_instance = MyClass() my_instance.class_method() my_instance.static_method() ``` 输出结果为: ``` This is a class method Class variable: Hello, world! This is a static method This is a class method Class variable: Hello, world! This is a static method ``` 希望这能回答你的问题!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值