简体   繁体   English

如何在同一个类中调用一个类的函数

[英]How to call function of a class in the same class

I am trying to call get_data function of class myclass in the same class but it returns this error. 我试图在同一类中调用类myclass的get_data函数,但它返回此错误。

get_data() missing 1 required positional argument: 'self' get_data()缺少1个必需的位置参数:“ self”

How can i call get_data() function in the class? 我如何在类中调用get_data()函数?

class MyClass:
    def get_data(self):
        return(1)
    a = get_data()
ab = MyClass()
print(ab.a)

Make use of class constructor __init__ 利用类构造器__init__

class MyClass:
    def __init__(self):
        self.a = self.get_data()

    def get_data(self):
        return(1)

ab = MyClass()
print(ab.a)

Also, notice I capitalized the class name to follow python classes naming convention. 另外,请注意,我将类名大写以遵循python类的命名约定。

You can't do that because you've made the function a bound method that takes the instance as the first argument but you're not passing any currently. 您无法执行此操作,因为已将函数设为绑定方法,该方法将实例作为第一个参数,但当前未传递任何参数。

I'm not sure what you're upto but you can refer the get_data method as name a (rather than calling), and call it after instantiating an instance: 我不确定您要做什么,但是您可以将get_data方法命名为a (而不是调用),并在实例化实例后调用它:

In [136]: class myclass: 
     ...:     def get_data(self): 
     ...:         return 1 
     ...:          
     ...:     a = get_data 
     ...:      
     ...: ab = myclass() 
     ...: print(ab.a())                                                                                                                                                                                     
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM