41. Python------ 类方法和静态调用
python修炼第十七天
2019年 4月7日 晴
class Dog:
type = "狗" # 类属性
@classmethod # @classmethod标识的方法为类方法
def get_info(cls): # 类方法第一个形参为cls, 对应的参数为类对象,也是解释器自动设置
print("类型为:%s" % cls.type)
# 调用类方法 类对象/实例对象都可以
Dog.get_info()
dog1 = Dog()
dog1.get_info()
class Cat:
def eat(self):
print("吃东西")
@staticmethod # @staticmethod标识的方法为静态方法
def eat(): # 静态方法默认既不传递实例对象, 也不传递类对象(节省性能)
print("喝东西")
# 调用静态方法 类对象/实例对象都可以调用
Cat.eat()
cat1 = Cat()
cat1.eat()
方法使用场景
- 方法中需要实例对象,定义实例方法
- 方法中需要使用类对象, 定义类方法
- 方法中既不需要实例对象,也不需要类对象,定义静态方法
D:\studing学习\python_67_类方法和静态方法.py
类型为:狗
类型为:狗
喝东西
喝东西
Process finished with exit code 0