# 1.6. 面向对象
class 类名:
#属性
#方法
def xxx(self):
yyyy
例如:
class person:
def hello(self):
print("hello")
def show(self):
print("name:",self.name,"age:",self.age)
tom=person()
tom.name="tom"#添加属性
tom.age=20
tom.hello()
print(tom.name)
tom.show()
aaa=person()
aaa.name="aaa"
aaa.age=23
aaa.show()
结果是:
hello
tom
name: tom age: 20
name: aaa age: 23
**self相当于this指针**
## ```__init__```方法
但不相当于构造函数
def 类名:
#初始化函数,用来完成一些默认的设定
def __init__():
pass
1. 无参数的:
class person:
def __init__(self):
self.name="person"
self.age=0
def hello(self):
print("hello")
def show(self):
print("name:",self.name,"age:",self.age)
bbb = person()
bbb.show()
结果是:
name: person age: 0
2. 有参数的:
class person:
def __init__(self,name,age):
self.name=name
self.age=age
def hello(self):
print("hello")
def show(self):
print("name:",self.name,"age:",self.age)
bbb = person("bbb",12)
bbb.show()
结果是:name: bbb age: 12
## ```__str__()```方法
相当于Java中的toString()方法
class person:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return "name:"+self.name+"age:"+str(self.age)
def hello(self):
print("hello")
def show(self):
print("name:",self.name,"age:",self.age)
bbb = person("bbb",12)
print("str:",bbb)
bbb.show()
结果是:
str: name:bbbage:12
name: bbb age: 12