1.静态方法:
1.编写时:
- 方法定时上面一行写 @staticmethod
- 方法的参数可有可无;
但是在方法里不能使用实例对象封装的值
2.调用时:
- 类名.方法名()
- 对象.方法名()
3.什么时候用到静态方法?
- 无需调用对象已封装的值
2.类方法
1.编写时:
- 方法定时上面一行写 @classmethod
- 方法的参数:至少有一个cls参数
2.调用时:
- 类名.方法名() #默认会将当前类传到参数cls中
- 对象.方法名() # 也可行
3.什么时候用到类方法?
- 如果在方法中用到当前类,可以定义类方法
3.属性(方法):
1.编写时:
- 方法定时上面一行写 @property
- 方法的参数:只能有一个self , 因为调用的时候只要一个函数名不传参
2.调用时:
- 类名.方法名()
对象.方法名 # 不用带括号
3.什么时候用到类方法?
- 方法功能简单,无需传参
- 属性方法都有返回值
举例:
import time
class Foo:
@property
def method_with_property(self): ##含有@property
self.fasdfa=100
return 15
@staticmethod #static静态方法一定不能使用 实例中封装的值
def display_max(x, y):
max = x if x > y else y
print("max is:", max)
return max
@classmethod
def show(cls , x1, x2):
print("cls , x1, x2 is : ", cls , x1, x2)
@property
def end_func(self):
def start(self):
return time.time()
a = Foo()
#对象调用:
b = a.method_with_property
print(a.method_with_property)
a.display_max(11, 21)
a.show('xxx', 'yyy')
print('#' * 30)
#通过类调用:
f = Foo
print(f.method_with_property)
f.display_max(11, 21)
f.show('xxx', 'yyy')
输出结果
15 ——有区别
max is: 21
cls , x1, x2 is : <class '__main__.Foo'> xxx yyy
##############################
<property object at 0x000001C78AC90CC0> ——有区别
max is: 21 _相同
cls , x1, x2 is : <class '__main__.Foo'> xxx yyy _相同
通过比较可知道:
@property 属性方法 通过类名调用返回的是一个对象,并没有执行此函数
所以属性方法只能通过实例对象来调用