定义类
class 类名[(父类)]:
类体
创建和使用
animal = Animal()
print(animal) *#<__main__.Animal object at 0x0000019A01FBBEB0>*
print打印对象必须重写_str_()方法
类成员
成员变量
1.实例变量
2.类变量
属性
成员方法
1.实例方法
2.类方法
3.静态方法
class Person(object):
def __init__(self,age,name,weight):
# pass
self.age = age
self.name = name
self.weight = weight
person1 = Person()
print("{0}".format(person1.age)) #没有给构造器传入参数,所以是错误的
#正确的是
person2 =Person(18,'小明',70)
print('年龄:{0} ,姓名:{1} ,体重 :{2}'.format(person2.age,person2.name,person2.weight
class Person(object):
grade = '大二'
def __init__(self,age,name,weight):
# pass
self.age = age
self.name = name
self.weight = weight
class Person(object):
grade = '大二'
def __init__(self,age,name,weight):
# pass
self.age = age
self.name = name
self.weight = weight
def eat(self):
self.weight += 10
print('--eat--')
def run(self):
self.weight -= 10
print('--run--')
person3 =Person(19,'小明',70)
print('小明的体重是:{0}'.format(person3.weight))
#通过实例调用方法
person2.eat()
print('小明的体重是:{0}'.format(person3.weight))
person3.run()
print('小明的体重是:{0}'.format(person3.weight))
class Person(object):
grade = '大二'
def __init__(self,age,name,weight):
# pass
self.age = age
self.name = name
self.weight = weight
def eat(self):
self.weight += 10
print('--eat--')
def run(self):
self.weight -= 10
print('--run--')
**@classmethod #类方法的装饰器
def add(cls,sex): #申明类方法时注意前面要用cls
return cls.grade + sex #只能调用类变量或类方法**
me = Person.add(':男')
print(me)
class Person(object):
grade = '大二'
def __init__(self,age,name,weight):
# pass
self.age = age
self.name = name
self.weight = weight
def eat(self):
self.weight += 10
print('--eat--')
def run(self):
self.weight -= 10
print('--run--')
@classmethod #类方法的装饰器
def add(cls,sex): #申明类方法时注意前面要用cls
return cls.grade + sex #只能调用类变量或类方法
@staticmethod #静态方法的装饰器
def jing(sex): #申明静态方法时注意前面什么都不需要
return Person.add(sex)
me1 = Person.jing(':女')
print(me1)
me2 = Person(19,'小明',70)
print(me2.jing(':不男不女'))