Python类方法和实例对象的方法

class	Person:

    def say_hi(self):
        print('Hello, how are you?')
        
p = Person()
p.say_hi()         #这里不能由引号
Person.say_hi('')    #缺引号会提示错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的方法实例方法有什么区别? 方法通过装饰器@classmethod进行修饰,可以通过名或实例对象来调用。而实例方法属于方法型的函数,只能通过实例化后的对象来调用。 方法实例方法之间的功能差异在于调用方式和作用范围上也有所不同。方法有两种调用方式,一种是通过名来调用,另一种是通过实例化后的对象来调用。而静态方法也有两种调用方式,一种是通过名来调用,另一种是通过实例化后的对象来调用。实例方法只能通过实例化后的对象来调用。 举个例子来说明: ```python class FunctionTest: fun = "test" def __init__(self): self.__name = "function" self.__age = 2 @classmethod def execute_class(cls): logging.info("this is class method!") @staticmethod def execute_static(x): logging.info("this is static method!") logging.info(f"{x} is a num.") def execute_normal(self): logging.info("This is normal method!") if __name__ == '__main__': # 实例化调用 FT = FunctionTest() FT.execute_normal() # 实例化调用 FT.execute_static(7) FT.execute_class() # 名调用 FunctionTest.execute_static(9) FunctionTest.execute_class() ``` 在上面的例子中,`execute_class`是一个方法,可以通过名或实例化后的对象来调用。而`execute_static`是一个静态方法,也可以通过名或实例化后的对象来调用。而`execute_normal`是一个实例方法,只能通过实例化后的对象来调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值