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
shimingzhoudf
V2EX  ›  Python

Python 调用类方法问题

  •  
  •   shimingzhoudf · 2019-03-26 16:13:31 +08:00 · 2211 次点击
    这是一个创建于 1830 天前的主题,其中的信息可能已经有所发展或是发生改变。

    class A(object): def func(self,i): print(i)

    A.func(None,1)

    不用实例化也能调用该方法?这样写法对吗,合理不

    10 条回复    2019-03-27 16:37:00 +08:00
    j0hnj
        1
    j0hnj  
       2019-03-26 16:15:29 +08:00
    没问题。说实话你跑一下不就知道了
    pythonbug
        2
    pythonbug  
       2019-03-26 16:43:16 +08:00
    Python 菜鸡一只, 水平很低, 说错了请各位大佬指正, 先谢过了.

    class A(object):
    def func(self, i):
    print(i)

    @classmethod
    def func1(cls, i):
    print(i)


    A().func(1) # 输出 1, 实例对象调用实例方法, 实例方法的 self 指向实例对象
    A.func(None, 1) # 输出 1, 类对象调用实例方法
    A.func1(1) # 输出 1, 类对象调用类方法
    A().func1(1) # 输出 1, 实例对象调用类方法

    我没见过用类对象调用实例方法的例子(应该是我见识少?), 如果要用类对象调用一个方法可以定义一个类方法, 在方法名上加 @classmethod 装饰器, 方法第一个形参一般为 cls
    pythonbug
        3
    pythonbug  
       2019-03-26 16:46:04 +08:00
    我见识少, 只是觉得用类调用实例方法有点怪, 也不知道是否有啥弊端还是怎样
    HelloAmadeus
        4
    HelloAmadeus  
       2019-03-26 18:12:37 +08:00 via iPhone
    python 实现就是这样,实例调用方法默认把 self 传进去了,实际的执行的就是类定义的方法.
    ipwx
        5
    ipwx  
       2019-03-26 18:19:04 +08:00
    @classmethod 是特殊 decorator,不要以常理笃之。
    arischow
        6
    arischow  
       2019-03-26 18:20:03 +08:00 via iPhone
    instance.method 是糖
    jmc891205
        7
    jmc891205  
       2019-03-26 18:22:31 +08:00
    这样写法在 Python 中是合法的
    但是在日常开发中是不合理的
    如果一个类的某个方法和其实例无关,还是加上 classmethod 装饰器吧
    yushenglin
        8
    yushenglin  
       2019-03-26 19:05:32 +08:00
    这样写是可以的,但是不建议使用,你还可以用类名加私有变量名对私有属性进行修改呢,这在日常工作中不太符合规范,但是能用。
    Kilerd
        9
    Kilerd  
       2019-03-26 20:01:53 +08:00
    instance.method(parameters)

    equals to

    Class.method(instance, parameters)
    xpresslink
        10
    xpresslink  
       2019-03-27 16:37:00 +08:00
    python 有这么用的,比如自己写一个类的工厂函数。
    但是最好加上 @staticmethod 装饰。就可以省去第一个位置参数了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5317 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:14 · PVG 16:14 · LAX 01:14 · JFK 04:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.