栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从另一个类调用类方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从另一个类调用类方法

更新:刚刚

call_user_func_array
在您的帖子中看到了对它的引用。那不一样。用于
getattr
获取函数对象,然后使用您的参数调用它

class A(object):    def method1(self, a, b, c):        # foomethod = A.method1

method
现在是一个实际的函数对象。可以直接调用(函数是python中的一流对象,就像PHP>
5.3中一样)。但是下面的考虑仍然适用。也就是说,除非您
A.method1
使用下面讨论的两个装饰器中的一个进行装饰,将其
A
作为第一个参数传递给实例或在的实例上访问方法,否则以上示例将爆炸
A

a = A()method = a.method1method(1, 2)

您有三种选择

  1. 使用的实例
    A
    进行呼叫
    method1
    (使用两种可能的形式)
  2. classmethod
    装饰器应用于
    method1
    :您将不再能够引用其中
    self
    method1
    但在这种情况下,您将
    cls
    在该位置传递一个实例
    A
  3. 在应用
    staticmethod
    装饰器
    method1
    :您将不再能够引用
    self
    ,或
    cls
    staticmethod1
    但你可以硬编码到引用
    A
    到它,但很明显,这些文献将被所有子类继承
    A
    ,除非他们专门覆盖
    method1
    ,不叫
    super

一些例子:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up    def method1(self, a, b):        return a + b    @staticmethod    def method2(a, b):        return a + b    @classmethod    def method3(cls, a, b):        return cls.method2(a, b)t = Test1()  # same as doing it in another classTest1.method1(t, 1, 2) #form one of calling a method on an instancet.method1(1, 2)        # form two (the common one) essentially reduces to form oneTest1.method2(1, 2)  #the static method can be called with just argumentst.method2(1, 2)      # on an instance or the classTest1.method3(1, 2)  # ditto for the class method. It will have access to the classt.method3(1, 2)      # that it's called on (the subclass if called on a subclass)# but will not have access to the instance it's called on# (if it is called on an instance)

请注意,就像

self
变量名完全取决于您一样,变量名也完全取决于您,
cls
但这些是常规值。

现在您知道该怎么做了,我会认真考虑 是否 要这样做。通常,本应被称为未绑定(无实例)的方法最好保留为python中的模块级函数。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号