Directorio
1. Crea tu propia clase de objeto
- Python proporciona listas, tuplas, diccionarios, colecciones, muchas estructuras de datos integradas.
- Cuando la estructura de datos incorporada no puede cumplir con los requisitos, Python le permite definir su propia estructura de datos
- Integre los datos y operaciones (funciones) requeridas juntas - objetos
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
ganning = {'name':'甘宁', 'country':'吴','hp':4, 'damage':2}
zhangchunhua = {'name':'张春华', 'country':'魏','hp':3, 'damage':1}
¡Tantos héroes, es aterrador pensar en ello! ! ! ! ! !
- ¿Cómo construir rápidamente cada héroe?
Usar clase
1 Crear una clase
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)
Análisis de código
class People0:
def inf(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
- clase: palabra clave para crear una clase
- People_0: nombre de clase
- def inf ...: la función definida en la clase, generalmente llamada *** método ***
Análisis de código
p0 = People_0()
p0.inf('jack', 5, 0)
- p0 = People_0 (): crea una instancia
- p0.inf ('jack', 5, 0): métodos de llamada en la clase
self: la instancia misma, el primer parámetro de cada método (función definida en la clase) es self
p0.name
'jack'
¿Hay alguna forma más conveniente?
*** __ init __ ***: un método especial de la clase
- Este método se llama automáticamente cuando se instancia la clase
- Nota: Hay dos izquierda y derecha _
#创建类
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__方法中,称为:属性
-类内定义的函数称为:方法
实例化数据称为:实例
¿Por qué se fue el país ?
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. Herencia
- Comenzar desde 0 no es una buena manera
- Puedes subir más rápido pisando los hombros de gigantes
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
Análisis de código
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
- héroe de clase: definición de clase
- (People): People es la clase que se hereda, llamada *** clase padre ***
- def __init __ (self, name, hp, damage, country): crea un método llamado automáticamente para almacenar atributos
- People .__ init __ (self, name, hp, damage): hereda los atributos de la clase padre
- self.country = country: atributos únicos
liufeng = Hero('刘封', 4, 2, '蜀')
liufeng.country
'蜀'
liufeng.name
'刘封'
Quiero que la clase tenga más funciones.
3. Crear un método de clase
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>>
Todavía quiero ver peleas
[Falló la transferencia de la imagen de la cadena externa, el sitio de origen puede tener un mecanismo de cadena antirrobo, se recomienda guardar la imagen y cargarla directamente (img-nQlYhNdH-1586488644386) (archivo adjunto: 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. Módulos y paquetes
Definición básica:
- módulo : cualquier sufijo es un
*.py
archivo. El nombre del módulo es el nombre del archivo. - módulo incorporado: función incorporada del compilador de Python, no hay un
.py
archivo correspondiente . - paquete : Python3.3 o superior, cualquier carpeta puede considerarse como un paquete.
- objeto : Básicamente todo en Python es un objeto: funciones, clases, variables, etc.
1. importar
Carga
Cuatro casos de sintaxis de importación:
import <package>
import <module>
from <package> import <module or subpackage or object>
# Función 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
¿Se puede cargar mi archivo py?
import division
division.my_dicision3(1,2)
0.5
Quiero agregar un arma al héroe, pero el arma está escrita en otra parte. . . . . .
#载入外部已创建好的武器类
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
阵营:吴