学习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 numpy 一维数组转变为多维数组的实例

python numpy 一维数组转变为多维数组的实例

如下所示: import numpy new_list = [i for i in range(9)] numpy.array(new_list).reshape(3,3) 借助n...

Dlib+OpenCV深度学习人脸识别的方法示例

Dlib+OpenCV深度学习人脸识别的方法示例

前言 人脸识别在LWF(Labeled Faces in the Wild)数据集上人脸识别率现在已经99.7%以上,这个识别率确实非常高了,但是真实的环境中的准确率有多少呢?我没有这方...

python采集百度百科的方法

本文实例讲述了python采集百度百科的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf-8 -*- #encoding...

Python实现的微信红包提醒功能示例

本文实例讲述了Python实现的微信红包提醒功能。分享给大家供大家参考,具体如下: #coding=utf-8 import itchat from itchat.content i...

详解Python的迭代器、生成器以及相关的itertools包

对数学家来说,Python这门语言有着很多吸引他们的地方。举几个例子:对于tuple、lists以及sets等容器的支持,使用与传统数学类似的符号标记方式,还有列表推导式这样与数学中集合...