V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-06-28 12:31:47 +08:00 · 1571 次点击
    这是一个创建于 1762 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2019-06-29 17:58:14 +08:00
    Sylv
        1
    Sylv  
       2019-06-28 12:36:42 +08:00
    __init__ 是类的初始化方法,fun 只能在类初始化后才能运行。简而言之,请重看 Python 基础教程。
    xiri
        2
    xiri  
       2019-06-28 12:37:45 +08:00 via Android
    拿不到吧,这里的 init 相当于 C++中的构造函数,在对象声明的时候就调用结束了,而这时候 input_num 还没有输入
    18870715400
        3
    18870715400  
    OP
       2019-06-28 12:43:12 +08:00
    谢谢,刚刚试了直接在 fun 中初始化 a 属性
    leishi1313
        4
    leishi1313  
       2019-06-28 12:45:33 +08:00 via Android
    你好,你这种情况我们一般不建议用类的呢,用函数就可以了亲
    18870715400
        5
    18870715400  
    OP
       2019-06-28 12:51:51 +08:00
    class A():
    a = None
    def __init__(self):
    pass

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


    已解决,谢谢各位
    shyrock
        6
    shyrock  
       2019-06-28 13:13:59 +08:00
    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
        7
    lowman  
       2019-06-29 17:56:47 +08:00
    class A(object):
    def __init__(self):
    print("--------------")
    self.a = self.func()
    print(self.a)



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

    A()
    lowman
        8
    lowman  
       2019-06-29 17:58:14 +08:00
    感觉很奇妙, init 是初始化实例对象, 可居然能在 init 方法里调用 实例对象的方法. 龟叔果然厉害.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5326 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 03:44 · PVG 11:44 · LAX 20:44 · JFK 23:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.