静态方法
类方法
属性方法
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
属性方法的作用就是通过@property把一个方法变成一个静态属性
#-*- encoding:utf8 -*- #Wind clear raise class Dog(): member = 0 def __init__(self, name): self.name = name def walk(self): print("walk function") @staticmethod # 无法通过self访问属性、方法 def talk(self): #self.walk() print("Talk now is: ", self.name) class Animal(object): name = "类变量" def __init__(self, name): self.name = name @classmethod # 设置方法只能访问类变量,无法访问类属性 def talk(self): print("The Animal talk:", self.name) class Person(object): def __init__(self, name): self.name = name @property # 将一个方法设置为属性 def eat(self): # 无法通过Person.eat()调用 print(self.name, "is eating") return "hel" d = Dog("DD") #d.talk("aaaaa") #AttributeError: 'str' object has no attribute 'name' d.talk(d) a = Animal("Dark") a.talk() p = Person("Fengqingyang") s = p.eat print("return [%s]" % s)
Talk now is: DD
The Animal talk: 类变量
Fengqingyang is eating
return [hel]
二、特殊属性及成员
__doc__ __class__ __module__ __dict__
class Dog():
"""Dog doc content"""
###
#-*- encoding:utf8 -*-
#Wind clear raise
from 类的特殊属性方法_2 import Dog
class Foo(object):
"""doc内容"""
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
print("__call__:", args, kwargs)
f = Foo("Wind")
print(Foo.__doc__)
print(f.__class__, f.__module__)
d = Dog()
print(d.__module__, d.__class__)
print(d.__doc__)
f("hello", name="test")
#Foo("")("call", age=333)
print(Foo.__dict__) # 类的所有属性成员
print(f.__dict__) # 实例的所有属性成员
f.name = "dict测试"
print(Foo.__dict__) # 结果内容不变
print(f.__dict__) # 实例内容name变更
“”“
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /data/youngboy/youngboy/study/day07/类的特殊属性方法.py
doc内容
<class '__main__.Foo'> __main__
类的特殊属性方法_2 <class '类的特殊属性方法_2.Dog'>
Dog doc content
__call__: ('hello',) {'name': 'test'}
{'__init__': <function Foo.__init__ at 0x1021df378>, '__module__': '__main__', '__call__': <function Foo.__call__ at 0x1021df400>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': 'doc内容', '__weakref__': <attribute '__weakref__' of 'Foo' objects>}
{'name': 'Wind'}
{'__init__': <function Foo.__init__ at 0x1021df378>, '__module__': '__main__', '__call__': <function Foo.__call__ at 0x1021df400>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': 'doc内容', '__weakref__': <attribute '__weakref__' of 'Foo' objects>}
{'name': 'dict测试'}
Process finished with exit code 0
”“”
2、__str__、__getitem__、__setitem__ __delitem__
class Dog(): """Dog doc content""" def __init__(self, name): self.name = name def __str__(self): ##print(d) return "Wind" def test(self): pass def __getitem__(self, item): # 调用时触发 print("getitem: ", item) def __setitem__(self, key, value): print("setitem: ", key, value) # 设置时触发 def __delitem__(self, key): # 删除时触发 print("del:", key) d = Dog("Dog") print(d) result = d["k"] # 触发 __getitem__ d["k"] = "setkey" # 触发 __setitem del d["k"] # 触发__delitem__
"""
Wind
getitem: k
setitem: k setkey
del: k
"""
类的另类定义:
def func(self): print("hello Wind ", self.name, self.age) def __init__(self,name, age): self.name = name self.age = age # 利用逼格定义类, 同时也说明python一切皆对象 Foo = type('Foo2', (object,), {'talk': func, '__init__': __init__}) # 类名 type(object_or_name, bases, dict) f = Foo("Wind", 33) f.talk() print(type(f)) print(type(Foo))
hello Wind Wind 33
<class '__main__.Foo2'>
<class 'type'>
类的生成 调用 顺序依次是 __new__ --> __call__ --> __init__


1 class Foo(object): 2 def __init__(self): 3 print("init") 4 5 def __call__(self, *args, **kwargs): 6 print("hello call") 7 8 def __new__(cls, *args, **kwargs): 9 print("hello new") 10 return object.__new__(cls) # 去继承父类的__new__方法 11 # 类似 F.__init__(self) 12 13 14 f = Foo()
hello new
init
__new__ 在实例化之前干点什么事
class Foo(object):
def __init__(self, name):
self.name = name
print("init")
def __call__(self, *args, **kwargs):
print("hello call")
def __new__(cls, *args, **kwargs):
print("hello new")
# return object.__new__(cls) # 去继承父类的__new__方法
# 类似 F.__init__(self)
f = Foo()
print(type(f))
程序结果 f 没有真正的创建,so,在init之前运行了new
<class 'NoneType'>
反射
class Foo(object):
def walk(self):
print("walk")
def talk(msg=""):
print("hello talk")
s = input(">>").strip()
obj =Foo()
if hasattr(obj, s):
v = getattr(obj, s)
v()
else:
setattr(obj, s, talk)
v = getattr(obj, s)
v()
print(dir(obj))
'''
>>input_str
hello talk
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'input_str', 'walk']
'''
异常:
1 a = [] 2 s = {} 3 s[1] = "hello" 4 5 try: 6 # a[3] 7 # b 8 # c = 1 9 # s[2] 10 open("aaa") 11 except (IndexError, KeyError) as e: # 多个异常写在一起 12 print("异常 ", e) 13 except NameError as e: # 单个异常 14 print("异常", e) 15 except Exception as e: 16 print("各种异常:", e) 17 else: # 无异常 18 print("无异常") 19 finally: # 最终 20 print("无论有无异常、表示感谢") 21 22 23 class MyException(BaseException): # 自定义异常 24 def __init__(self, msg): 25 self.msg = msg 26 27 # 重载父类 __str__, 父类默认直接 return self.msg 28 # def __str__(self): 29 # print("str....") # 先输出 str... 然后输出msg 30 # return self.msg 31 32 33 try: 34 raise MyException("我的异常") # 直接抛出异常 35 except MyException as e: # 36 print("自定义: ", e)