类的声明:Class
# 声明一个类 经典类
class Dog:
# 类文档字符串
'狗类'
# 声明一个类 新式类
class People(object):
'人类'
# 数据属性
idNum = "1234456"
# 方法属性
def eatFood():
print("吃饭")
def work(self):
print("工作")
# py3中 都是新式类
属性访问:
# 实例化一个对象
one = People()
# 访问对象的属性
print(one.idNum)
People.eatFood()
People.work("adfaf")
# 查看类的属性名字
print(dir(People))
# 查看类的属性字典 访问类的属性实际就是访问类的属性字典里面的值
print(People.__dict__)
# 类名
print(People.__name__)
# 类文档
print(People.__doc__)
构造函数:__init__
class People(object):
"人类"
# 类属性
sex = "male"
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 构造一个对象
one = People("bill", 12)
# 访问对象的属性
print(one.name)
# 实例对象可以访问类属性
# 类比于方法嵌套作用域,内层方法__init__可以访问外层Class嵌套中的属性
print(one.sex)
print(People.__dict__)
print(one.__dict__)
属性的增删改查:
class People(object):
"人类"
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 构造一个对象
one = People("bill", 12)
# 修改属性
one.name = "alex"
# 删除属性
del one.name
# 增加属性
one.idnum = 12222
静态属性:
使用系统提供的装饰器方法:@property
class People(object):
"人类"
def __init__(self, name, age):
self.name = name
self.age = age
@property
def eatFood(self):
print("吃饭")
# 构造一个对象
one = People("bill", 12)
one.eatFood
类方法:
使用系统提供的装饰器方法:@classmethod
class People(object):
"人类"
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def eatFood(cls):
print("吃饭")
People.eatFood()
静态方法:
使用系统提供的装饰器方法:@staticmethod
class People(object):
"人类"
@staticmethod
def eatFood():
print("静态方法")
def __init__(self, name, age):
self.name = name
self.age = age
People.eatFood()
网友评论