[小白系列]Python面向对象以及模块和包简介,直接从例子入手,这边看过来

一、 创建自己的对象–类

  • python 提供了列表、元组、字典、集合,诸多内置数据结构
  • 当内置数据结构不能满足需求时,python允许定义自己的数据结构
  • 将所需数据和操作(函数)整合在一起–对象
liufeng = {'name':'刘封', 'country':'蜀','hp':4, 'damage':2}
ganning = {'name':'甘宁', 'country':'吴','hp':4, 'damage':2}
zhangchunhua = {'name':'张春华', 'country':'魏','hp':3, 'damage':1}

那么多英雄,想想都恐怖!!!!!!

  • 如何快速构建每一个英雄呢?

使用类

1 创建类

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)

代码解析

class People0:
    def inf(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
  • class:创建类的关键词
  • People_0:类名
  • def inf…:类中定义的函数,一般称为***方法***

代码解析

p0 = People_0()
p0.inf('jack', 5, 0)
  • p0 = People_0():创建实例
  • p0.inf(‘jack’, 5, 0):调用类中方法

self:实例本身,每个方法(类内定义的函数)第一个参数都是self

p0.name
'jack'

有没有更便捷的方法?

***__init__***:类的一个特殊方法

  • 该方法在类实例化时会自动调用
  • 注意:init左右各两个_
#创建类
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__方法中,称为:属性
    -类内定义的函数称为:方法
  • 实例化数据称为:实例

country 为什么不见了?

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. 继承

  • 从0开始不是一个好方法
  • 踩着巨人的肩膀,才能爬的更快
class Hero(People):
    def __init__(self,name, hp, damage, country):
        People.__init__(self, name, hp, damage)
        self.country = country

代码解析

class Hero(People):
    def __init__(self,name, hp, damage, country):
        People.__init__(self, name, hp, damage)
        self.country = country
  • class Hero:类定义
  • (People):People是所要继承的类,称为***父类***
  • def __init__(self,name, hp, damage, country):创建自动调用的方法,用于存放属性
  • People.__init__(self, name, hp, damage):继承父类的属性
  • self.country = country:特有属性
liufeng = Hero('刘封', 4, 2, '蜀')
liufeng.country
'蜀'
liufeng.name
'刘封'

我想要类有更多功能

3. 创建类内方法

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>>

我还想看打架

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(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
阵营:吴

二、 模块、包

基本定义:

  • module: 任何后缀为*.py文件. 模块名称就是文件名称.
  • built-in module: python编译器内置的函数,没有对应的.py文件.
  • package: python3.3以上,任何文件夹都可以视为包.
  • object: python中基本所有的东西都为对象: 函数,类,变量等。

1. import

载入

import 语法的四种情况:

  • import <package>
  • import <module>
  • from <package> import <module or subpackage or object> # 变量 函数
  • from <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

自己的py文件可以载入吗?

import division
division.my_dicision3(1,2)
0.5

我想给英雄添加武器,但武器在其他地方写好了。。。。。。

#载入外部已创建好的武器类
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
阵营:吴
发布了42 篇原创文章 · 获赞 28 · 访问量 4961

猜你喜欢

转载自blog.csdn.net/KaelCui/article/details/105429214
今日推荐