推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
18870715400
V2EX  ›  Python

关于 Python 中的类想请教一下大佬

  •  
  •   18870715400 · Jun 28, 2019 · 2389 views
    This topic created in 2695 days ago, the information mentioned may be changed or developed.
    class A():
        def __init__(self):
            self.a = np.random.rand(len(self.input_num[0]))
    
        def fun(self, input_num):
            pass
    
    

    如上代码所示,init 中如何能够拿到 fun 方法中的 input_num 输入呢,上面代码显示是错误的,假设 input_num 只在 fun 函数中输入,

    8 replies  •  2019-06-29 17:58:14 +08:00
    Sylv
    Sylv
    Jun 28, 2019
    1
    __init__ 是类的初始化方法,fun 只能在类初始化后才能运行。简而言之,请重看 Python 基础教程。
    imkuang
    imkuang
    Jun 28, 2019 via Android
    2
    拿不到吧,这里的 init 相当于 C++中的构造函数,在对象声明的时候就调用结束了,而这时候 input_num 还没有输入
    18870715400
    18870715400
    OP
    Jun 28, 2019
    3
    谢谢,刚刚试了直接在 fun 中初始化 a 属性
    leishi1313
    leishi1313
    Jun 28, 2019 via Android
    4
    你好,你这种情况我们一般不建议用类的呢,用函数就可以了亲
    18870715400
    18870715400
    OP
    Jun 28, 2019
    5
    class A():
    a = None
    def __init__(self):
    pass

    def fun(self, input_num):
    self.a = np.random.rand(len(input_num[0]))


    已解决,谢谢各位
    shyrock
    shyrock
    Jun 28, 2019
    6
    class A():
    a = None
    def __init__(self,input_num):
    fun(input_num)

    def fun(self, input_num):
    self.a = np.random.rand(len(input_num[0]))

    行吗?
    lowman
    lowman
    Jun 29, 2019
    7
    class A(object):
    def __init__(self):
    print("--------------")
    self.a = self.func()
    print(self.a)



    def func(self):
    a = input("======================:")
    return a

    A()
    lowman
    lowman
    Jun 29, 2019
    8
    感觉很奇妙, init 是初始化实例对象, 可居然能在 init 方法里调用 实例对象的方法. 龟叔果然厉害.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2764 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 10:23 · PVG 18:23 · LAX 02:23 · JFK 05:23
    ♥ Do have faith in what you're doing.