版权声明:本文为博主原创文章,未经博主允许不得转载,希望能在相互交流中共同成长。【大红色:一级标题 绿色:二级标题 二红色:三级标题 黄色:四级标题】 https://blog.csdn.net/admin_maxin/article/details/83618796
0.普通方法
普通方法访问类属性:self.__class__.类属性名称
class Test(object):
n = 123
def __init__(self, n):
self.n = n
def tell(self):
# 调用类变量
print("类n: %s" % self.__class__.n)
print("实例n: %s" % self.n)
if "__main__" == __name__:
t1 = Test(456)
t1.tell()
1.静态方法
①静态方法是类中的函数,不需要实例
②主要用来存放逻辑性的代码,与类本身没有交互,即在静态方法中不会涉及到类内的方法和属性若想调用类内的方法和属性则可通过(__class__.类属性)
③形式:添加@staticmethod装饰器
④调用:类名 或 实例
import time
class TimeTest(object):
n = 100
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
@staticmethod
def showTime():
print(__class__.n)
return time.strftime("%H:%M:%S", time.localtime())
if "__main__" == __name__:
t = TimeTest(12, 23, 45)
t.showTime()
TimeTest.showTime()
2.类方法
①将类本身作为对象进行操作的方法
②与类方法的区别:不管是实例调用还是类调用,第一个传入的对象都是类
③cls即为类自身
④只能访问类变量,不能访问实例变量
⑤可以通过实例 / 类 进行调用
class ClassTest(object):
__num = 0
@classmethod
def addNum(cls):
cls.__num += 1
@classmethod
def getNum(cls):
print(cls.__num)
# 魔术函数:创建实例的时候调用人数累加的函数
def __new__(cls, *args, **kwargs):
ClassTest.addNum()
return super(ClassTest, cls).__new__(cls)
class Student(ClassTest):
def __init__(self, name=""):
self.name = name
if "__main__" == __name__:
s1 = Student("1")
s3 = Student("3")
ClassTest.getNum()
s3.getNum()
3.属性方法
在面向对象编程中,经常会将对某个属性(为了安全设置成私有属性)的操作封装成某些函数。而@property正是通过装饰器,将类内部进行属性操作的函数设置成“属性”的形式进行调用。
class Score(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property
def score(self):
print(self.__score)
@score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError("invalid score")
self.__score = score
# # error
# @property
# def set_score(self, score):
# if score < 0 or score > 100:
# raise ValueError("invalid score")
# self.__score = score
#
# @property
# def get_score(self):
# print(self.__score)
if "__main__" == __name__:
s1 = Score("maxin", 91)
s1.score # 91
s1.score = 95
s1.score # 95
4.实例(属性、方法的绑定)和类(属性、方法的绑定)
python作为一种动态语言,允许对传入的实例进行实例和方法的绑定,对属性的绑定比较简单,对方法的绑定需要通过from types import MethodType 的形式,告诉解释器s.set_age的方法操作是将set_age函数绑定s 即 s.set_age = MethodType(set_age, s) ,这样python就知道怎样执行s的set_age方法
class Student(object):
pass
def set_age(self, age):
self.age = age
def set_score(self, score):
self.score = score
if "__main__" == __name__:
# 实例:动态绑定属性
s1 = Student()
s1.name = "maxin"
print(s1.name)
# 实例:动态绑定方法
from types import MethodType
s1.set_age = MethodType(set_age, s1)
s1.set_age(35)
print(s1.age)
# 类:动态方法绑定
Student.set_score = set_score
s2 = Student()
# s2.set_age(22) # error
s1.set_score(90)
s2.set_score(78)
print(s1.score, s2.score)
# 类:动态属性绑定
Student.name = "maxin"
s3 = Student()
s4 = Student()
s3.__class__.name = "limingyue"
print(s3.name, s4.name)