Annuaire
1. Créez votre propre classe d'objets
- Python fournit des listes, des tuples, des dictionnaires, des collections, de nombreuses structures de données intégrées
- Lorsque la structure de données intégrée ne peut pas répondre aux exigences, Python vous permet de définir votre propre structure de données
- Intégrez ensemble les données et opérations (fonctions) requises - objets
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
ganning = {'name':'甘宁', 'country':'吴','hp':4, 'damage':2}
zhangchunhua = {'name':'张春华', 'country':'魏','hp':3, 'damage':1}
Tant de héros, c'est terrifiant d'y penser! ! ! ! ! !
- Comment construire rapidement chaque héros?
Utiliser la classe
1 Créer une classe
class People_0:
def inf(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
p0 = People_0()
p0.inf('jack', 5, 0)
Analyse de code
class People0:
def inf(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
- classe: mot-clé pour créer une classe
- People_0: nom de classe
- def inf…: la fonction définie dans la classe, généralement appelée *** méthode ***
Analyse de code
p0 = People_0()
p0.inf('jack', 5, 0)
- p0 = People_0 (): créer une instance
- p0.inf ('jack', 5, 0): méthodes d'appel dans la classe
self: l'instance elle-même, le premier paramètre de chaque méthode (fonction définie dans la classe) est self
p0.name
'jack'
Existe-t-il un moyen plus pratique?
*** __ init __ ***: une méthode spéciale de la classe
- Cette méthode est automatiquement appelée lorsque la classe est instanciée
- Remarque: Il y a deux gauche et droite _
#创建类
class People:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
#创建实例
p1 = People('张三', 6, 0)
#类对象
p1.damage
0
一般将数据放在__init__方法中,称为:属性
-类内定义的函数称为:方法
实例化数据称为:实例
Pourquoi le pays est-il parti?
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
class People:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
2. Héritage
- Partir de 0 n'est pas un bon moyen
- Vous pouvez grimper plus vite en marchant sur les épaules de géants
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
Analyse de code
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
- héros de classe: définition de classe
- (People): People est la classe à hériter, appelée *** classe parent ***
- def __init __ (auto, nom, hp, dommages, pays): créer une méthode appelée automatiquement pour stocker les attributs
- People .__ init __ (self, name, hp, damage): hérite des attributs de la classe parente
- self.country = country: attributs uniques
liufeng = Hero('刘封', 4, 2, '蜀')
liufeng.country
'蜀'
liufeng.name
'刘封'
Je veux que la classe ait plus de fonctions
3. Créez une méthode de classe
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
def get_inf(self): #不要忘记self
"""获取实例信息"""
print("姓名:{}".format(self.name))
print("攻击力:{}".format(self.damage))
print("当前血量:{}".format(self.hp))
print("阵营:{}".format(self.country))
liufeng = Hero('刘封', 4, 2, '蜀')
ganning = Hero('甘宁', 4, 2, '吴')
liufeng.get_inf()
姓名:刘封
攻击力:2
当前血量:4
阵营:蜀
ganning.get_inf()
姓名:甘宁
攻击力:2
当前血量:4
阵营:吴
调用类内属性的时候,不加(),调用类内方法的时候,需要加()
# 调用类内方法时,不要忘记()
ganning.get_inf
<bound method Hero.get_inf of <__main__.Hero object at 0x10c58b210>>
Je veux toujours regarder les combats
[Le transfert de l'image de la chaîne externe a échoué, le site source peut avoir un mécanisme de chaîne antivol, il est recommandé d'enregistrer l'image et de la télécharger directement (img-nQlYhNdH-1586488644386) (pièce jointe: fight.jpg)]
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
def get_inf(self): #不要忘记self
"""获取实例信息"""
print("姓名:{}".format(self.name))
print("攻击力:{}".format(self.damage))
print("当前血量:{}".format(self.hp))
print("阵营:{}".format(self.country))
def attack(self,enemy):
"""self攻击enemy
enemy血量减少
enemy血量计算方式:enemy当前血量 - self攻击力
"""
print(self.name)
print("攻击力为:{}".format(self.damage))
print("{}目前血量为:{}".format(enemy.name, enemy.hp))
print("{}攻击{}".format(self.name,enemy.name))
enemy.hp-=self.damage
print("{}剩余血量为:{}".format(enemy.name, enemy.hp))
print("***********************************")
#创建实例
liufeng = Hero('刘封', 4, 2, '蜀')
ganning = Hero('甘宁', 4, 2, '吴')
#产看ganning被打前信息
ganning.get_inf()
print('#################')
#liufeng攻击ganning
liufeng.attack(ganning)
#查看ganning被打后信息
ganning.get_inf()
姓名:甘宁
攻击力:2
当前血量:4
阵营:吴
#################
刘封
攻击力为:2
甘宁目前血量为:4
刘封攻击甘宁
甘宁剩余血量为:2
***********************************
姓名:甘宁
攻击力:2
当前血量:2
阵营:吴
2. Modules et packages
Définition de base:
- module : Tout suffixe est un
*.py
fichier. Le nom du module est le nom du fichier. - module intégré : fonction intégrée du compilateur Python, il n'y a pas de
.py
fichier correspondant . - package : Python3.3 ou supérieur, tout dossier peut être considéré comme un package.
- objet : Fondamentalement, tout en Python est un objet: fonctions, classes, variables, etc.
1. importation
Charge
Quatre cas de syntaxe d'importation:
import <package>
import <module>
from <package> import <module or subpackage or object>
# Fonction variablefrom <module> import <object>
math.sin(math.pi)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-765fc4c8de70> in <module>
----> 1 math.sin(math.pi)
NameError: name 'math' is not defined
import math
math.sin(math.pi)
1.2246467991473532e-16
help(math)
Help on module math:
NAME
math
MODULE REFERENCE
https://docs.python.org/3.7/library/math
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(x, /)
Find x!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(x, y, /)
greatest common divisor of x and y
hypot(x, y, /)
Return the Euclidean distance, sqrt(x*x + y*y).
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
pow(x, y, /)
Return x**y (x to the power of y).
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
/Users/edz/opt/anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so
Puis-je charger mon fichier py?
import division
division.my_dicision3(1,2)
0.5
Je veux ajouter une arme au héros, mais l'arme est écrite ailleurs. . . . . .
#载入外部已创建好的武器类
import weapon
#创建武器实例
dao = weapon.Weapon('圆月弯刀', 1)
#产看ganning装备武器前的属性
ganning.get_inf()
print('#############')
#将武器dao装备给ganning,提升ganning攻击力
dao.take_weapon(ganning)
print('##############')
#查看ganning装备武器后的属性
ganning.get_inf()
姓名:甘宁
攻击力:2
当前血量:4
阵营:吴
#############
将武器圆月弯刀装备给英雄甘宁
甘宁的攻击力变为3
##############
姓名:甘宁
攻击力:3
当前血量:4
阵营:吴