table of Contents
1. Create your own object-class
- Python provides lists, tuples, dictionaries, collections, many built-in data structures
- When the built-in data structure cannot meet the requirements, Python allows you to define your own data structure
- Integrate required data and operations (functions) together – objects
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
ganning = {'name':'甘宁', 'country':'吴','hp':4, 'damage':2}
zhangchunhua = {'name':'张春华', 'country':'魏','hp':3, 'damage':1}
So many heroes, it is terrifying to think about it! ! ! ! ! !
- How to quickly build each hero?
Use class
1 Create a class
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)
Code analysis
class People0:
def inf(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
- class: keyword to create a class
- People_0: class name
- def inf…: the function defined in the class, generally called *** method ***
Code analysis
p0 = People_0()
p0.inf('jack', 5, 0)
- p0 = People_0 (): create an instance
- p0.inf ('jack', 5, 0): call methods in the class
self: the instance itself, the first parameter of each method (function defined in the class) is self
p0.name
'jack'
Is there a more convenient way?
*** __ init __ ***: a special method of the class
- This method is automatically called when the class is instantiated
- Note: There are two left and right _
#创建类
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__方法中,称为:属性
-类内定义的函数称为:方法
实例化数据称为:实例
Why is the country gone?
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. Inheritance
- Starting from 0 is not a good way
- You can climb faster by stepping on the shoulders of giants
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
Code analysis
class Hero(People):
def __init__(self,name, hp, damage, country):
People.__init__(self, name, hp, damage)
self.country = country
- class Hero: class definition
- (People): People is the class to be inherited, called *** parent class ***
- def __init __ (self, name, hp, damage, country): Create an automatically called method for storing attributes
- People .__ init __ (self, name, hp, damage): inherit the attributes of the parent class
- self.country = country: unique attributes
liufeng = Hero('刘封', 4, 2, '蜀')
liufeng.country
'蜀'
liufeng.name
'刘封'
I want the class to have more functions
3. Create a class method
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>>
I still want to watch fights
[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-nQlYhNdH-1586488644386) (attachment: 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 and packages
Basic definition:
- module : Any suffix is a
*.py
file. The module name is the file name. - built-in module : Python compiler built-in function, there is no corresponding
.py
file. - package : Python3.3 or above, any folder can be regarded as a package.
- object : Basically everything in Python is an object: functions, classes, variables, etc.
1. import
Load
Four cases of import syntax:
import <package>
import <module>
from <package> import <module or subpackage or object>
# Variable functionfrom <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
Can my py file be loaded?
import division
division.my_dicision3(1,2)
0.5
I want to add a weapon to the hero, but the weapon is written elsewhere. . . . . .
#载入外部已创建好的武器类
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
阵营:吴