假设我们有两个函数都需要用到一个公共变量name,一种做法就是把这个变量放到类中,大家一起使用。
一个最简单的类的定义和使用如下。
- 定义类
class Person(object):
def hi(self): # 方法中的self指代具体对象,这是一个具体对象的方法。
print('hi')
def hello(self):
print('hello')
- 创建并使用对象(也称实例)
类是一个我们设计的一个模型,一般需要生成具体的对象进行使用。
kevin = Person() # 创建对象
kevin.hi() # 调用对象方法
kevin.hello()
如果这个对象只需要使用一次,也可以不赋值给变量直接使用Person().hi()
注意调用Person和调用Person()是不一样的操作,Person指使用这个类,Person()则表示创建一个新对象。
有时候,我们想要在创建对象时为其传入一些参数,比如name,这个可以通过类的__init__
方法来接收并将其变为对象的熟悉。
class Person(object):
def __init__(self, name): # self指代对象,默认参数新建对象时不用传,name则在新建对象时传入
self.name = name # 将接收到name绑定给self(即对象)的name属性
这样类中的所有方法都可以使用self.name来获取到这个属性。
class Person(object):
def __init__(self, name):
self.name = name
def hi(self):
print(f'hi, {self.name}')
def hello(self):
print(f'hello, {self.name}')
在创建对象时需要传入__init__
方法中self以外的参数。
kevin = Person('凯文')
kevin.hi()
kevin.hello()
另外,类的熟悉会自动绑定给对象,即在方法中可以使用self.
来访问,如。
class Person(object):
place = 'earth'
def __init__(self, name):
self.name = name
def hi(self):
print(f'hi, {self.name}, I'm on {self.place}') # 使用self.place访问从类继承来的属性
def hello(self):
print(f'hello, {self.name}')