一、定义一个类
class 类名():
类的属性
对象属性
类的方法
对象方法
class Person(object):
name = 'tom' //类属性
def hello(self): //对象方法
print(Person.name) //类调用类属性
print(self.name) //对象调用类属性
二、对象的定义
对象名 = 类名()
使用 对象名,属性或对象名,方法
p = Person()
print(p.name) //对象名调用类属性
print(Person.name) //类名调用类属性
#p.hello() //对象名调用对象方法
#Person.hello(p) //类在初始化时,就将对象添加到self中,如果不加参数p会报错参数缺失
#Person.hello(Person())
三、构造方法和析构方法
class Person(object):
def __init__(self,name='tom',age=19): //构造方法
self.name = name //对象属性
self.age = age
def __del__(self): //析构方法
print(self.name)
print(self.age)
print('对象销毁了')
p = Person() //创建一个对象
print(p.name) //对象名调用对象属性
print(p.age)
//Person是类名,调用对象属性会报错
AttributeError: type object 'Person' has no attribute 'name' 类无法访问对象的属性
print(Person.name)
print(Person.age)
//类名想要调用对象属性,要变成对象
print(Person().name)
print(Person().age)