# 使用普通的函数调用
import time
def foo():
# do something
time.sleep(1)
start = time.time()
foo()
end = time.time()
print(f"foo() took {end - start} seconds to run.")
# 使用装饰器
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__}() took {end - start} seconds to run.")
return result
return wrapper
@timer # 相当于 foo = timer(foo)
def foo():
# do something
time.sleep(1)
foo()
# 不使用@property装饰器
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def set_name(self, name):
if not isinstance(name, str):
raise TypeError("name must be a string")
self.name = name
def get_age(self):
return self.age
def set_age(self, age):
if not isinstance(age, int):
raise TypeError("age must be an integer")
if age < 0 or age > 150:
raise ValueError("age must be between 0 and 150")
self.age = age
p = Person("kira", 40) # 实例化
print(p.get_name()) # kira
print(p.get_age()) # 40
p.set_name("勇哥")
p.set_age(35)
print(p.get_name()) # 勇哥
print(p.get_age()) # 35
# 使用@property装饰器
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if not isinstance(name, str):
raise TypeError("name must be a string")
self._name = name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if not isinstance(age, int):
raise TypeError("age must be an integer")
if age < 0 or age > 150:
raise ValueError("age must be between 0 and 150")
self._age = age
p = Person("kira", 30)
print(p.name) # kira
print(p.age) # 30
p.name = "勇哥"
p.age = 35
print(p.name) # 勇哥
print(p.age) # 35
# 不使用__slots__属性
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("勇哥", 90)
print(p.__dict__)
print(p.__sizeof__())
输出
{'name': '测试玩家勇哥', 'age': 90}
32
# 使用__slots__属性
class Person:
# 指定该类只能拥有name和age两个属性
__slots__ = ("name", "age")
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 20)
print(p.__sizeof__())
print(p.__dict__)
输出
Traceback (most recent call last):
File "D:\app\apitest\debug\ts.py", line 82, in <module>
print(p.__dict__) # AttributeError: 'Person' object has no attribute '__dict__'
AttributeError: 'Person' object has no attribute '__dict__'
32