学习python类方法与对象方法

yipeiwu_com5年前Python基础

本文实例针对python的类方法与对象方法进行学习研究,具体内容如下

class Test_Demo:
  TEST = 'test_value'

  def __init__(self,name,age):
    self.name = name
    self.age = age
  #static method
  @staticmethod
  def test_static():
    return Test_Demo.TEST
  #特性
  @property
  def test_property(self):
    return self.name+':'+str(self.age)
  #类方法
  @classmethod
  def test_class(self):
    return self.TEST

if __name__ == '__main__':
  test_demo = Test_Demo('zj',23)
  #print(test_demo.name)
  print(Test_Demo.test_static())
  print(test_demo.test_property)
  print(test_demo.test_class())

输出结果:

注:与php不同的是:

 类方法和静态方法可以访问类的静态变量(类变量,TEST),但都不能访问实例变量(即name,age)

 如果访问了就会报错:

以上就是本文的全部内容吗,希望对大家的学习有所帮助。

相关文章

python操作kafka实践的示例代码

python操作kafka实践的示例代码

1、先看最简单的场景,生产者生产消息,消费者接收消息,下面是生产者的简单代码。 #!/usr/bin/env python # -*- coding: utf-8 -*- impor...

python比较两个列表大小的方法

本文实例讲述了python比较两个列表大小的方法。分享给大家供大家参考。具体如下: L1 = [1, ('a', 3)] L2 = [1, ('a', 2)] print L1 &l...

python基于json文件实现的gearman任务自动重启代码实例

一:在gearman任务失败后,调用task_failed def task_failed(task, *args): info = '\n'.join(args) dat...

django 通过URL访问上传的文件方法

django 通过URL访问上传的文件方法

Django2.0 通过URL访问上传的文件(pdf、picture等) Django是一个成熟的web框架,基于python实现,有很多的优点,很容易快速上手(详见官网:https:/...

Python multiprocessing.Manager介绍和实例(进程间共享数据)

Python中进程间共享数据,处理基本的queue,pipe和value+array外,还提供了更高层次的封装。使用multiprocessing.Manager可以简单地使用这些高级接...