43(2304楼)课后习题的类静态方法:
装饰器——@classmethod @staticmethod @property
对应拓展内容的python内置的修饰符有三个,分别是 staticmethod、classmethod 和 property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。
由于模块里可以定义函数,所以静态方法和类方法的用处并不是太多--------别让这最后一句给坑了
@staticmethod的使用,是在定义函数的时候不用写self了,且静态方法不能访问类变量和实例变量(源自:https://www.cnblogs.com/shijingjing07/p/5321198.html)
具体如下:
class A:
example = 1
def __init__(self):
self.number = 10
@staticmethod
def smark():
print('这是静态函数么?',self.example)
def nsmark(self):
print('这不是静态函数么?',self.number)
def nsmark1(self):
print(self.example)
example在静态方法中去掉self也是无法访问的
类方法能实现的功能都可以通过定义一个普通函数来实现,只要这个函数接受一个类对象做为参数就可以了)
对于类对象__new__(cls,*params)
这个params就是你输入的东西,比如
class C: #C后面()里的参数是它的基类*3
c = C(1,2,3) #C后面()里的对应的是params的内容
继承的基类是动态的,则通过为基类定义别名,然后子类继承别名的方式比较便利,tip get
类的静态方法:下午继续
class C:
@staticmethod # 该修饰符表示 static() 是静态方法
def static(arg1, arg2, arg3):
print(arg1, arg2, arg3, arg1 + arg2 + arg3)
def nostatic(self,arg1,arg2):
print(arg1, arg2, arg1 + arg2)
运行结果如下:
>>> A = C()
>>> B = C()
>>> A.static(1,2,3)
1 2 3 6
>>> A.nostatic(1,2)
1 2 3
>>> C.static(1,2,3)
1 2 3 6
>>> C.nostatic(1,2)
Traceback (most recent call last):
File "<pyshell#99>", line 1, in <module>
C.nostatic(1,2)
TypeError: nostatic() missing 1 required positional argument: 'arg2'
>>> C.nostatic(1,2,3)
2 3 5
即类也能够直接调用非静态方法,但是需要给self传递值
魔法方法str和repr的的区别:
class Test(object):
def __init__(self,value='abc'):
self.data = value
class TestRepr(Test):
def __repr__(self):
a = 'TestRepr(%s)'%self.data
return a
str返回对象的地址,repr返回的是对象的内容