---恢复内容开始---

类方法:通过@classmethod装饰器实现,类方法和普通方法的区别是,类方法只能访问类变量,不能访问实例变量,代码如下:

  1. class Person(object):
  2. def __init__(self,name):
  3. self.name = name
  4. @classmethod
  5. def eat(self):
  6.  
  7. print("%s is eating"%self.name)
  8. d = Person("alex")
  9. d.eat()

报错如下:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类方法.py
  2. Traceback (most recent call last):
  3. File "D:/python开发代码/Python之路/作业/day8/类方法.py", line 9, in <module>
  4. d.eat()
  5. File "D:/python开发代码/Python之路/作业/day8/类方法.py", line 7, in eat
  6. print("%s is eating"%self.name)
  7. AttributeError: type object 'Dog' has no attribute 'name'

定义一个类变量后,代码如下:

  1. class Person(object):
  2. name = "parktrick"
  3. def __init__(self,name):
  4. self.name = name
  5. @classmethod
  6. def eat(self):
  7.  
  8. print("%s is eating"%self.name)
  9. d = Person("alex")
  10. d.eat()

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类方法.py
  2. parktrick is eating
  3.  
  4. Process finished with exit code 0

静态方法:@staticmethod装饰器即可把其装饰的方法变为一个静态方法,静态方法的特点是不可以访问实例变量或类变量,但是可以调用时主动传递实例本身给eat方法,即d.eat(d),操作代码如下:

未使用类名调用方法的场景:

  1. class Dog(object):
  2. def __init__(self,name):
  3. self.name = name
  4. @staticmethod #把eat变成静态方法
  5. def eat(self):
  6. print("%s is eating"%self.name)
  7. d = Dog("alex")
  8. #调用时主动传递实例本身给eat方法,即d.eat(d)
  9. d.eat()

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
  2. Traceback (most recent call last):
  3. File "D:/python开发代码/Python之路/作业/day8/静态方法.py", line 9, in <module>
  4. d.eat()
  5. TypeError: eat() missing 1 required positional argument: 'self'
  6.  
  7. Process finished with exit code 1

报错显示eat方法需要个参数,但我们明明传了alex啊,所以说静态方法无法访问实例中的变量,那定义一个类变量呢?看下面:

  1. class Dog(object):
  2. name = "parktrick" #定义了一个类变量,看看运行结果
  3. def __init__(self,name):
  4. self.name = name
  5. @staticmethod #把eat变成静态方法
  6. def eat(self):
  7. print("%s is eating"%self.name)
  8. d = Dog("alex")
  9. #调用时主动传递实例本身给eat方法,即d.eat(d)
  10. d.eat()

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
  2. Traceback (most recent call last):
  3. File "D:/python开发代码/Python之路/作业/day8/静态方法.py", line 10, in <module>
  4. d.eat()
  5. TypeError: eat() missing 1 required positional argument: 'self'
  6.  
  7. Process finished with exit code 1

结果显示报错,所以由此可以看出静态方法无法访问实例变量和类变量

看看正确姿势,通过调用时主动传递实例本身给eat方法,代码如下:

  1. class Dog(object):
  2. # name = "parktrick"
  3. def __init__(self,name):
  4. self.name = name
  5. @staticmethod #把eat变成静态方法
  6. def eat(self):
  7. print("%s is eating"%self.name)
  8. d = Dog("alex")
  9. #调用时主动传递实例本身给eat方法,即d.eat(d)
  10. d.eat(d)

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
  2. alex is eating
  3.  
  4. Process finished with exit code 0

属性方法:通过@property把一个方法变成一个静态属性,既然是属性,就可以直接使用实例化对象调用了,比如d.walk,代码如下:

  1. class Person(object):
  2. def __init__(self,name):
  3. self.name = name
  4. @property
  5. def walk(self):
  6. print("%s is walking"%self.name)
  7. test = Person("Parktrick")
  8. test.walk #直接使用实例化对象调用walk,不用加小括号

运行结果如下:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/属性方法.py
  2. Parktrick is walking
  3.  
  4. Process finished with exit code 0

如果加了括号就会报错了,结果如下所示:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/属性方法.py
  2. Traceback (most recent call last):
  3. File "D:/python开发代码/Python之路/作业/day8/属性方法.py", line 8, in <module>
  4. test.walk()
  5. TypeError: 'NoneType' object is not callable
  6. Parktrick is walking

静态属性的作用:

比如一个航班当前的状态,是到达了还是延迟了,取消了还是已经飞走了,想知道这种状态需要经历以下几步:

1. 连接航空公司API查询

2. 对查询结果进行解析

3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以了。代码如下:

  1. class Flight(object):
  2. def __init__(self,name):
  3. self.flight_name = name
  4. def check_status(self):
  5. print("check flight %s status" %self.flight_name)
  6. return 1
  7. @property
  8. def flight_status(self):
  9. status = self.check_status()
  10. # print(status)
  11. if status == "":
  12. print("飞机已起飞")
  13. elif status == "":
  14. print("飞机未起飞")
  15. elif status == "":
  16. print("飞机就没有飞过")
  17. @flight_status.setter #修改
  18. def flight_status(self,status):
  19. status_dic = {
  20. 0:"flying",
  21. 1:"not flying",
  22. 2:"none flying"
  23. }
  24. print("\033[31mHas changed the flight status to \033[0m",status_dic.get(status))
  25.  
  26. test = Flight("国航")
  27. # test.check_status()
  28. test.flight_status
  29. test.flight_status = 2

运行结果如下:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/航班.py
  2. check flight 国航 status
  3. Has changed the flight status to none flying
  4.  
  5. Process finished with exit code 0

再看一个廖大神举的例子:

  1. class Student(object):
  2. @property
  3. def score(self):
  4. return self._score
  5. @score.setter
  6. def score(self,value):
  7. if not isinstance(value,int):
  8. raise ValueError("score must be an integer")
  9. if value < 0 or value > 100:
  10. raise ValueError("score must be 0-100")
  11. self._score = value
  12. test = Student()
  13. test.score = 100
  14. print(test.score)

总而言之,Python内置的@property装饰器就是负责把一个方法变成属性调用的。

类的特殊成员方法

__doc__

  1. class Person(object):
  2. '''测试类的成员变量'''
  3. def walk(self):
  4. pass
  5. P = Person()
  6. print(P.__doc__)

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
  2. 测试类的成员变量
  3.  
  4. Process finished with exit code 0

__dict__ 查看类或对象中的所有成员

  1. class Province:
  2. country = "china"
  3. def __init__(self,name,count):
  4. self.name = name
  5. self.count = count
  6. def func(self,*args,**kwargs):
  7. print("func")
  8. #获取类的成员,即:静态字段、方法
  9. print(Province.__dict__)
  10.  
  11. obj1 = Province("Hebei",10000)
  12. print(obj1.__dict__)
  13. #获取对象obj1的成员

__getitem__、__setitem__、__delitem__

  1. class Foo(object):
  2. def __getitem__(self, key):
  3. print('__getitem__', key)
  4.  
  5. def __setitem__(self, key, value):
  6. print('__setitem__', key, value)
  7.  
  8. def __delitem__(self, key):
  9. print('__delitem__', key)
  10. obj = Foo()
  11. result = obj["k1"] #自动触发执行__getitem__
  12. obj["k2"] = "alex" #自动触发执行__setitem
  13. del obj["k1"]

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
  2. __getitem__ k1
  3. __setitem__ k2 alex
  4. __delitem__ k1
  5.  
  6. Process finished with exit code 0

反射:通过字符串映射或修改程序运行时的状态、属性、方法

利用反射查看面向对象成员归属

  1. class Foo:
  2. def __init__(self,name):
  3. self.name = name
  4. def show(self):
  5. print("show")
  6. obj = Foo("as")
    #如果是类,就可以找到类中成员,运行结果为Bool值,找到了就显示True,没找到就显示False
  7. print(hasattr(Foo,"show"))
    #如果是对象,既可以找到对象,也可以找到类中的成员
  8. print(hasattr(obj,"name"))
  9. print(hasattr(obj,"show"))

运行结果:

  1. C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
  2. True
  3. True
  4. True
  5.  
  6. Process finished with exit code 0

未完待续。。。。

python类的高级属性的更多相关文章

  1. Python 类的高级属性(可选)

    1.slots实例:限制类的实例有合法的属性集,只有__slots__属性列表中的属性才可能成为实例属性. 对象的实例通常没有一个属性字典,可以在__slots__列表中包含一个属性字典__dict_ ...

  2. Python 类的私有属性与私有方法

    1.隐藏的使用场景 在Python类中,有些属性和方法只希望在对象的内部被使用,而不希望在外部被访问到, 2.定义方式, 在属性名或方法名前增加两个下划线,定义的就是私有属性或方法 #其实这仅仅这是一 ...

  3. Python——类的高级主题

    介绍关于类的一些高级主题,这些是可选的,在Python应用程序中,不会常常遇到. =========================================================== ...

  4. python 类的私有属性和方法 (转载)

    转载:http://www.runoob.com/python/python-object.html 类属性与方法 类的私有属性 __private_attrs:两个下划线开头,声明该属性为私有,不能 ...

  5. Python 简明教程 --- 20,Python 类中的属性与方法

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 与客户保持良好的关系可以使生产率加倍. -- Larry Bernstain 目录 类中的变量称为属 ...

  6. Python类的私有属性

    class Bar(object): __age = 18 sex = 'male' def __init__(self, ): pass def f(self): print(self.__age) ...

  7. Python类的特殊属性

    Python中的特殊属性 定义如下类: class Foo(object): """Foo class definition""" 类的特殊 ...

  8. Python类的实例属性详解

    实例属性 1.类被实例化后才会具有的属性 2.一般在_init_()方法中创建并初始化 3.直接使用即定义:self.<属性名> 4.引用方法:self.<属性名> 5.sel ...

  9. python类的__slots__属性、__del__属性、上下文(__enter__和__exit__)、

    常规情况下,类的属性字典是共享的,而实例的字典是独立的.如果一个类的属性较少,但是拥有很多的实例,这些实例的属性字典会占用较多的内存空间.对这样的类来说,为了节省内存空间,可以使用__slots__类 ...

随机推荐

  1. 关于QString中的arg()函数使用方法

    例:正确做法:ui->label->setText(QString("Processingfile%1").arg(index));错误做法: ui->label ...

  2. UIScrollView 实践经验(转)

    转载自:http://tech.glowing.com/cn/practice-in-uiscrollview/ UIScrollView(包括它的子类 UITableView 和 UICollect ...

  3. socket 实例化方法

      #!/usr/bin/env python # encoding: utf-8 import socket ip_port = ('127.0.0.1',9999) sk = socket.soc ...

  4. 绘制图形与3D增强技巧(三)----三角形图元TRANGLE

    1. glBegin(GL_TRANGLES); ........ glend(); 2.多边形的环绕方向:逆时针和顺时针的正反面 GLFront(GL_CCW)和GLFront(GL_CW); 3. ...

  5. 【windows】跑大型程序时不要休眠和睡眠

    win10系统. 为了节能,长时间没有操作操作系统会自动进入休眠模式. 先前设定了"控制面板\硬件和声音\电源选项\编辑计划设置",都设定为"从不",结果不起作 ...

  6. 【BZOJ-3306】树 线段树 + DFS序

    3306: 树 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 792  Solved: 262[Submit][Status][Discuss] De ...

  7. Chrome编辑了样式或者JS之后自动同步回本地工程

    比如我用HBuilder进行调试,在Chrome上修改了几个样式,我们通常的做法是,拷贝修改后的地方,然后再进行覆盖. 现在有了全自动的操作,在Chrome上修改了样式之后,通过Sources的Sav ...

  8. 文件内容统计——Linux wc命令

    有了该命令,就可以得到当前目录下所有符合条件的文件总数,如下: find -type f | wc -l 这个命令的功能也很好记,因为它功能很有限: wc -c filename:显示一个文件的字节数 ...

  9. [NOIP2015] 提高组 洛谷P2678 跳石头

    题目背景 一年一度的“跳石头”比赛又要开始了! 题目描述 这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石.组委会已经选择好了两块岩石作为比赛起点和终点.在起点和终点之间,有 N 块岩石(不 ...

  10. 帝国CMS文章随机调用等一些常用标签

    1.帝国CMS文章随机调用等一些常用标签 [e:loop={'news',10,18,0,'newstime>UNIX_TIMESTAMP()-86400*7','onclick desc'}] ...