class Student:
m_Name = '张韶涵' # 类属性,所有对象所共有
def __init__(self, age):
self.m_Age = age #实例属性
pass
def __str__(self):
return '姓名:{},年龄:{}'.format(self.m_Name, self.m_Age)
pass
stu1 = Student(18)
print(stu1) # 类实例化对象访问
print(Student(19)) # 类名直接访问m_Name,传值给m_Age
print(stu1.m_Age) # 仍未18,不因上面一条语句而改变
stu1.m_Name = '李易峰' # 改变了所有类对象的m_Name
stu2 = Student(25)
print(stu2) # 名字改变
stu1.m_Age = 50
print(stu2.m_Age)
stu2.m_Age = 10
print(stu1.m_Age)
print()
类方法:类对象所共有的方法,需要用装饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数
# 类方法可以被类对象,实例对象调用
class Person:
m_Country = 'China'
def __init__(self, name):
self.m_Name = name
@classmethod
def Get_Country(cls):
return cls.m_Country # 类函数访问类属性
@classmethod
def Change_Country(cls, country):
cls.m_Country = country
return cls.m_Country
def __str__(self):
return '姓名:{},国家:{}'.format(self.m_Name, self.m_Country)
print(Person('李易峰').Get_Country()) # 类对象直接调用类函数
p1 = Person('张韶涵')
print(p1.Get_Country())
print(p1)
print()
p2 = Person('易隆平')
print(p2)
print('背叛国家后')
p2.Change_Country('日本')
print(p2)
print(Person.m_Country)
print(Person.Change_Country('印度'))
print('再次叛国')
print(p2)
print()
类对象所拥有的方法,需要用@staticmenthod来表示静态方法,静态方法可以不加任何参数
class Student:
m_Class = '08121910'
def __init__(self, age):
self.m_Age = age
pass
@staticmethod
def Get_Class():
return Student.m_Class
pass
print(Student(10).Get_Class())
print()
import time
class Time:
@staticmethod
def Show_Time():
return time.strftime("%H:%M:%S", time.localtime())
pass
print(Time.Show_Time())
# 补充:类方法第一个参数为cls,实例方法第一个参数为self,且可以用self去引用类属性或者实例属性,如果存在实例属性和类属性重名的情况,实例属性的优先级最高
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- nryq.cn 版权所有 赣ICP备2024042798号-6
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务