面向对象
定义一个类
class Hero(object):
注意类的内容首行缩进
class Hero(object):
hero1 = Hero()
hero1
hero2.方法name,变量名进行调用
self
实例
class Hero(object):
def __init__(self, name, init_health=100, init_attack=10, alive=True):
self.name = name
self.health = init_health
self.attack = init_attack
self.alive = True
self.birth()
def attack_enemy(self, enemy):
enemy.health -= self.attack
if enemy.health <= 0:
enemy.alive = False
enemy.health = 0
print(f'{enemy.name} 死亡')
def upgrade(self):
self.attack *= 1.1
self.health *= 1.1
def birth(self):
print(f'我,{self.name},出生了!')
def recovery(self):
self.health += 100
访问限制
self.__attack = init_attack
self._health = init_health
class Hero(object):
def __init__(self, name, init_health=100, init_attack=10, alive=True):
self.name = name
self.health = init_health
self.__attack = init_attack
self.alive = True
self.__birth()
def attack_enemy(self, enemy):
enemy.health -= self.attack
if enemy.health < 0:
enemy.alive = False
enemy.health = 0
print(f'{enemy.name} 死亡')
def upgrade(self):
self.__attack *= 1.1
self.health *= 1.1
def __birth(self):
print(f'我,{self.name},出生了!')
def get_attack(self):
return self.__attack
def set_attack(self, value):
assert type(value)==int
if value > 10000:
value = 10000
self.__attack = value
Python内置类属性
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
类属性和类方法
类中的属性分为:
实例属性:对象所有,互不干扰
类属性:类所有,所有对象共享
类中的方法分为:
实例方法:定义中有self 参数
类方法:定义中有cls 参数,使用@classmethod 装饰器
静态方法:定义中即没有self 参数,也没有cls 参数,使用@staticmethod 装饰器
实例
class Hero(object):
version = 'v0.0.1'
def __init__(self, name, init_health=100, init_attack=10, alive=True):
self.name = name
self._health = init_health
self.__attack = init_attack
self.alive = True
self.__birth()
def attack_enemy(self, enemy):
enemy._health -= self.attack
if enemy._health < 0:
enemy.alive = False
enemy._health = 0
print(f'{enemy.name} 死亡')
def upgrade(self):
self.__attack *= 1.1
self._health *= 1.1
def __birth(self):
print(f'我,{self.name},出生了!')
def get_attack(self):
return self.__attack
@classmethod
def get_version(cls):
return cls.version
@classmethod
def set_version(cls, value):
cls.version = value
hero1.version = 'v0.0.3'
print(hero1.get_version(),hero2.get_version())
机器学习建模中的类
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(random_state=0,solver='newton-cg')
clf.fit(X, y)
clf.predict(X)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])