# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
类方法:被@classmethod装饰器装饰的方法
类方法一般是通过类名去调用的,并且自动将类名地址传给cls。
通过对象调用类方法也可以,但是传给cls的地址还是类名的地址。(一般不通过对象调用类方法)
类方法的作用:
1、在类的内部可以拿到类的地址,从而可以实例化对象
2、可以操作类的属性,如增删改查。(对象不能增删改类的属性)
"""
class Person:
def eat(self):
print('每天要吃饭')
@classmethod
def animal(cls): # 类方法, 注意被@classmethod装饰器装饰后,cls参数接收的是类名的地址
print('人类是高级动物!')
print(f'cls的地址:{cls}') # <class '__main__.Person'>
p2 = cls() # 类内 实例化对象
# 类方法一般通过类名调用
Person.animal()
print(Person) # <class '__main__.Person'>
# 类方法也可以通过对象调用
p1 = Person()
p1.animal()
# 统计实例化了几个对象
class Student:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Student.count_obj()
@classmethod
def count_obj(cls):
cls.count += 1
@classmethod
def get_count(cls):
return cls.count
s1 = Student('albert', 17)
s2 = Student('don', 21)
s3 = Student('hugu', 27)
print(Student.get_count())
"""
静态方法:被@staticmethod装饰器装饰的方法
静态方法是不依赖于对象与类的,其实静态方法就是函数,不需要实例。
静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,
也就是说在静态方法中,不会涉及到类中的属性和方法的操作。
"""
import time
# 定义一个关于时间操作的类
class TimeTest(object):
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
# 获取当前时间的函数,方法体中并没使用(也不能使用)类或实例的属性(或方法)
@staticmethod
def showTime():
return time.strftime("%H:%M:%S", time.localtime())
print(TimeTest.showTime())
t = TimeTest(2, 10, 10)
nowTime = t.showTime()
print(nowTime)
Python 类方法和静态方法
最新推荐文章于 2023-12-16 18:45:07 发布