python 面向对象高级特性
一、类与实例
1.类属性和实例属性
1). 类属性不管有多少个对象, 都只存储一份。
实例属性存储的个数取决于实例的个数.
2). 作用域不同:
类属性: 通过类名/对象名来访问
实例属性: 只能通过对象名来访问。
import random
class Turtle(object):
# power是类属性。
power = 100
def __init__(self):
# x,y:实例属性.
self.x = random.randint(0, 10)
self.y = random.randint(0, 10)
# 1). 类属性不管有多少个对象, 都只存储一份。 实例属性存储的个数取决于实例的个数.
# 2). 作用域不同:
# 类属性: 通过类名/对象名来访问
# 实例属性: 只能通过对象名来访问。
print(Turtle.power)
turtle1 = Turtle()
print(turtle1.power, turtle1.x, turtle1.y)
二、类方法和静态方法
1). @classmethod: 类方法
2). @staticmethod:静态方法
类方法能够通过实例对象和类对象去访问。
静态方法能够通过实例对象和类对象去访问。
1. @classmethod: 类方法
类方法是类对象所拥有的方法,需要用修饰器一般以@classmethod来标识其为类方法,
1). 对于类方法,第一个参数必须是类对象,作为第一个参数 (cls是形参, 可以修改为其它变量名,但最好用’cls’了)
2). 能够通过实例对象和类对象去访问
2. @staticmethod:静态方法
静态方法需要用修饰器一般以@staticmethod来标识其为静态方法,
1). 静态方法不需要多定义参数
2). 能够通过实例对象和类对象去访问
1). @classmethod: 类方法
2). @staticmethod:静态方法
"""
import random
class Turtle(object):
def __init__(self):
# x,y:实例属性.
self.x = random.randint(0, 10)
self.y = random.randint(0, 10)
self.power = 100
# 默认情况下, Python解释器会自动将对象传递给类里面定义的方法。
def eat(self):
print("self: ", self)
self.power += 20
@classmethod
def cls_example(cls):
print("cls: ", cls)
@staticmethod
def static_example():
print("静态方法.......")
turtle = Turtle()
turtle.eat()
turtle.cls_example()
turtle.static_example()
# 类方法能够通过实例对象和类对象去访问。
Turtle.cls_example()
# 静态方法能够通过实例对象和类对象去访问。
Turtle.static_example()
3.类方法和静态方法的应用
import time
"""
# 系统自带date类的使用
from datetime import date
dateObj = date(2019, 10, 10)
print(dateObj)
print(date.today())
"""
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return "%s-%s-%d" % (self.year, self.month, self.day)
@classmethod
def today(cls):
"""
返回当前的日期对象
cls: 类名称Date
:return: Date实例化的对象名称
"""
# 获取当前的时间, 返回的是命名元组的格式
# time.struct_time(tm_year=2019, tm_mon=12, tm_mday=29, tm_hour=16, tm_min=49, tm_sec=32, tm_wday=6, tm_yday=363, tm_isdst=0)
now = time.localtime()
return cls(now.tm_year, now.tm_mon, now