V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Mar 26, 2019 · 3026 views
    This topic created in 2590 days ago, the information mentioned may be changed or developed.

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

    A.func(None,1)

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

    10 replies    2019-03-27 16:37:00 +08:00
    j0hnj
        1
    j0hnj  
       Mar 26, 2019
    没问题。说实话你跑一下不就知道了
    pythonbug
        2
    pythonbug  
       Mar 26, 2019
    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  
       Mar 26, 2019
    我见识少, 只是觉得用类调用实例方法有点怪, 也不知道是否有啥弊端还是怎样
    HelloAmadeus
        4
    HelloAmadeus  
       Mar 26, 2019 via iPhone
    python 实现就是这样,实例调用方法默认把 self 传进去了,实际的执行的就是类定义的方法.
    ipwx
        5
    ipwx  
       Mar 26, 2019
    @classmethod 是特殊 decorator,不要以常理笃之。
    arischow
        6
    arischow  
       Mar 26, 2019 via iPhone
    instance.method 是糖
    jmc891205
        7
    jmc891205  
       Mar 26, 2019
    这样写法在 Python 中是合法的
    但是在日常开发中是不合理的
    如果一个类的某个方法和其实例无关,还是加上 classmethod 装饰器吧
    yushenglin
        8
    yushenglin  
       Mar 26, 2019
    这样写是可以的,但是不建议使用,你还可以用类名加私有变量名对私有属性进行修改呢,这在日常工作中不太符合规范,但是能用。
    Kilerd
        9
    Kilerd  
       Mar 26, 2019
    instance.method(parameters)

    equals to

    Class.method(instance, parameters)
    xpresslink
        10
    xpresslink  
       Mar 27, 2019
    python 有这么用的,比如自己写一个类的工厂函数。
    但是最好加上 @staticmethod 装饰。就可以省去第一个位置参数了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3332 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 77ms · UTC 13:08 · PVG 21:08 · LAX 06:08 · JFK 09:08
    ♥ Do have faith in what you're doing.