鱼C论坛

 找回密码
 立即注册
查看: 3028|回复: 8

[已解决]__init__ 里面的def 函数什么时候执行

[复制链接]
发表于 2022-10-14 16:27:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
class test(object):
    def __init__(self):
        print('s')
        def a():
            print('sss')


s = test()

def a() 怎么调用的
最佳答案
2022-10-14 19:08:19
非要嵌套放在 __init__ 里面,又要外部调用, 虽然也不是不可以(如下所示),但这样太怪了,甚至多余和混乱。
class test(object):
    def __init__(self):
        print('s')
        
        def a():
            print('sss')
        self.a = a

        
s = test()
s
s.a()   
sss

# 实际应该用不上 这样怪异的写法,还不如3楼那样直接定义和绑定。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-10-14 16:33:09 | 显示全部楼层
没调用
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-14 16:37:46 | 显示全部楼层
应该是缩进错误吧?我更改了一下!
class test(object):
    def __init__(self):
        print('s')
    def a():
        print('sss')
s = test()


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-14 16:45:10 | 显示全部楼层
本帖最后由 jackz007 于 2022-10-14 17:21 编辑

        1、__init__()是在实例化对象的时候被自动调用
s = test()    # __init__() 在这个时候被自动调用

        2、a() 是 __init__() 的内嵌函数,其作用域仅限于__init__()内,也就是说,只能供 __init__() 自己调用,如果在 __init__() 内没有被调用,那么,可以下断言,这个函数无用,出了__init__(),也就是出了内嵌函数 a() 的作用域,a() 根本就不可见,从而,无法被调用。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-14 19:08:19 | 显示全部楼层    本楼为最佳答案   
非要嵌套放在 __init__ 里面,又要外部调用, 虽然也不是不可以(如下所示),但这样太怪了,甚至多余和混乱。
class test(object):
    def __init__(self):
        print('s')
        
        def a():
            print('sss')
        self.a = a

        
s = test()
s
s.a()   
sss

# 实际应该用不上 这样怪异的写法,还不如3楼那样直接定义和绑定。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-14 19:20:06 | 显示全部楼层
class test(object):
    def __init__(self):
        print('s')
        def a():
            print('sss')
        a()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-14 22:57:53 | 显示全部楼层
init只在实例化对象的时候调用,如果这里面不使用a,之后就不可能在调用了
所以用self.a类似保存了这个函数吧,之后就可以屌用了
class test(object):
    def __init__(self):
        print('s')
        def a():
            print('sss')
        self.a = a


s = test()
s.a()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-10-17 11:23:33 | 显示全部楼层
本帖最后由 python鱼new 于 2022-10-17 11:34 编辑
阿奇_o 发表于 2022-10-14 19:08
非要嵌套放在 __init__ 里面,又要外部调用, 虽然也不是不可以(如下所示),但这样太怪了,甚至多余和混 ...


我在看一个项目,看懂了,它在最后调用了if get_google_credentials:
class KubeConfigLoader(object):

    def __init__(self, config_dict, active_context=None,
                 get_google_credentials=None,
                 config_base_path="",
                 config_persister=None,
                 temp_file_path=None):

        if config_dict is None:
            raise ConfigException(
                'Invalid kube-config. '
                'Expected config_dict to not be None.')
        elif isinstance(config_dict, ConfigNode):
            self._config = config_dict
        else:
            self._config = ConfigNode('kube-config', config_dict)

        self._current_context = None
        self._user = None
        self._cluster = None
        self.set_active_context(active_context)
        self._config_base_path = config_base_path
        self._config_persister = config_persister
        self._temp_file_path = temp_file_path

        def _refresh_credentials_with_cmd_path():
            config = self._user['auth-provider']['config']
            cmd = config['cmd-path']
            if len(cmd) == 0:
                raise ConfigException(
                    'missing access token cmd '
                    '(cmd-path is an empty string in your kubeconfig file)')
            if 'scopes' in config and config['scopes'] != "":
                raise ConfigException(
                    'scopes can only be used '
                    'when kubectl is using a gcp service account key')
            args = []
            if 'cmd-args' in config:
                args = config['cmd-args'].split()
            else:
                fields = config['cmd-path'].split()
                cmd = fields[0]
                args = fields[1:]

            commandTokenSource = CommandTokenSource(
                cmd, args,
                config.safe_get('token-key'),
                config.safe_get('expiry-key'))
            return commandTokenSource.token()

        def _refresh_credentials():
            # Refresh credentials using cmd-path
            if ('auth-provider' in self._user and
                'config' in self._user['auth-provider'] and
                    'cmd-path' in self._user['auth-provider']['config']):
                return _refresh_credentials_with_cmd_path()

            credentials, project_id = google.auth.default(scopes=[
                'https://www.googleapis.com/auth/cloud-platform',
                'https://www.googleapis.com/auth/userinfo.email'
            ])
            request = google.auth.transport.requests.Request()
            credentials.refresh(request)
            return credentials

        if get_google_credentials:
            self._get_google_credentials = get_google_credentials
        else:
            self._get_google_credentials = _refresh_credentials
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-10-17 11:24:21 | 显示全部楼层
本帖最后由 python鱼new 于 2022-10-17 11:33 编辑
阿奇_o 发表于 2022-10-14 19:08
非要嵌套放在 __init__ 里面,又要外部调用, 虽然也不是不可以(如下所示),但这样太怪了,甚至多余和混 ...


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-26 01:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表