#1.定义类
#语法
# class 类名():
# ...
# ...
# 注意 : 类名要遵守大驼峰命名规则(单词首字母大写)
# 创建对象
# 对象 = 类名()
class People():
def walk(self): # self 是指调用该函数的对象,类实例对象本身,类方法中的self参数,有点类似c++类this指针
print('can walk')
print(self)
# people = People()
# print(people)
# people.walk()
'''
输出
<__main__.People object at 0x00000277B62D7460>
can walk
<__main__.People object at 0x00000277B62D7460>
'''
#从这里可以看到,实例化对象和 self是同一个地址,所以self 就是实例化对象本身
class Man():
def hair(myself):
print('short hair')
print(myself)
man = Man()
print(man)
man.hair()
'''
输出
<__main__.Man object at 0x0000018875FD7460>
short hair
<__main__.Man object at 0x0000018875FD7460>
'''
#self可以取任意名字,不一定要用self,但是一般都用self
man1 = Man()
man1.hair()
# 输出
# short hair
# <__main__.Man object at 0x0000013D868D33D0>
#2.添加和获取对象属性
#2.1 类外面添加对象属性
class People():
def walk(self):
print('walk')
#输出对象属性
def print_info(self):
print(f'People 的age = {self.age}')
print(f'People de height = {self.height}')
peopel = People()
peopel.age = 20
peopel.height = 180
#2.2 类里面获取对象的属性
#语法 : self.属性名
peopel.print_info()
#注意,这里一定要先定义对象的属性,不然会报错 AttributeError: 'People' object has no attribute 'age'
#2.3 魔方方法
#在python中, __xx__()的函数叫做魔方方法,指的是具有特殊功能的函数
#3 魔方方法
#在python中, __xx__()的函数叫做魔方方法,指的是具有特殊功能的函数
#3.1 __init()__构造器,当一个实例被创建的时候调用的初始化方法 类似C++构造函数
class People():
def __init__(self, age = 0, height = 56.7, weight = 3.8):
self.age = age
self.height = height
self.weight = weight
def print_info(self):
print(f"People's age = {self.age}")
print(f"People's height = {self.height}")
print(f"People's weight = {self.weight}")
def __str__(self):
return "类的说明,或者对象状态的说明"
#注意,这里一定要返回str类型,不然报错 TypeError: __str__ returned non-string (type list)
def __del__(self):
print('对象销毁')
people = People()
people.print_info()
'''
输出
People's age = 0
People's height = 56.7
People's weight = 3.8
'''
print(people)
#3.2 __str__() 方法
#当使用print输出对象的时候,默认是输出对象的内存地址。
#如果定义了这个方法,那么就会打印这个方法中return 的数据
#3.3 __del__ ()方法 析构器,当一个实例被销毁的时候调用的方法
del people #输出 对象销毁
print('程序结束')