Diretório
1. Crie sua própria classe de objeto
- O Python fornece listas, tuplas, dicionários, coleções, muitas estruturas de dados internas
- Quando a estrutura de dados integrada não pode atender aos requisitos, o Python permite definir sua própria estrutura de dados
- Integrar dados e operações (funções) necessários juntos - objetos
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
ganning = {'name':'甘宁', 'country':'吴','hp':4, 'damage':2}
zhangchunhua = {'name':'张春华', 'country':'魏','hp':3, 'damage':1}
Tantos heróis, é aterrorizante pensar nisso! ! ! ! ! !
- Como construir rapidamente cada herói?
Usar classe
1 Crie uma turma
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álise de código
class People0:
def inf(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
- class: palavra-chave para criar uma classe
- People_0: nome da classe
- def inf…: a função definida na classe, geralmente chamada *** método ***
Análise de código
p0 = People_0()
p0.inf('jack', 5, 0)
- p0 = People_0 (): crie uma instância
- p0.inf ('jack', 5, 0): chama métodos na classe
self: a instância em si, o primeiro parâmetro de cada método (função definida na classe) é self
p0.name
'jack'
Existe uma maneira mais conveniente?
*** __ init __ ***: um método especial da classe
- Este método é chamado automaticamente quando a classe é instanciada
- Nota: Existem dois esquerdo e direito _
#创建类
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 que o país se foi?
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. Herança
- Começar de 0 não é uma boa maneira
- Você pode subir mais rápido pisando nos ombros de gigantes
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
Análise de código
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
- Herói da classe: definição de classe
- (Pessoas): Pessoas é a classe a ser herdada, chamada *** classe pai ***
- def __init __ (nome próprio, hp, dano, país): Crie um método chamado automaticamente para armazenar atributos
- Pessoas .__ init __ (auto, nome, hp, dano): herda os atributos da classe pai
- self.country = country: atributos únicos
liufeng = Hero('刘封', 4, 2, '蜀')
liufeng.country
'蜀'
liufeng.name
'刘封'
Eu quero que a classe tenha mais funções
3. Crie um método 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>>
Eu ainda quero assistir brigas
[Falha na transferência da imagem da cadeia externa, o site de origem pode ter um mecanismo de cadeia anti-roubo, é recomendável salvar a imagem e enviá-la diretamente (img-nQlYhNdH-1586488644386) (anexo: 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 e pacotes
Definição básica:
- module : Qualquer sufixo é um
*.py
arquivo.O nome do módulo é o nome do arquivo. - módulo embutido : função interna do compilador Python, não há
.py
arquivo correspondente . - pacote : Python3.3 ou superior, qualquer pasta pode ser considerada como um pacote.
- objeto : Basicamente, tudo em Python é um objeto: funções, classes, variáveis, etc.
1. importação
Carregar
Quatro casos de sintaxe de importação:
import <package>
import <module>
from <package> import <module or subpackage or object>
# Função variávelfrom <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
Meu arquivo py pode ser carregado?
import division
division.my_dicision3(1,2)
0.5
Quero adicionar uma arma ao herói, mas a arma está escrita em outro lugar. . . . . .
#载入外部已创建好的武器类
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
阵营:吴