繁体   English   中英

在方法中使用类属性

[英]Use class attribute in method

import pandas as pd
simpledata = pd.DataFrame({"A" : [1,2,3,4,5], 
                           "B" : [6,7,8,9,0], 
                           "C" : ["A", "B", "A", "D", "E"], 
                           "F" : [1.3, 2.4, 3.5, 5.6, 6.7]})
class MyViz:
    def __init__(self, df):
        self.simplelen = len(df)

    def simpleprint(self):
        print(self.simplelen)

MyViz.simpleprint(simpledata)

错误:

AttributeError: 'DataFrame' object has no attribute 'simplelen'

我需要的只是 simpleprint 方法中数据集的 len。

另一种尝试

class MyViz:
    def __init__(self, df):
        self.simplelen = len(df)

    def getlen(self):
        return len(self)

    def simpleprint(self):
        print(self.getlen(self))

MyViz.simpleprint(simpledata)

错误:

AttributeError: 'DataFrame' object has no attribute 'getlen'

您需要一个MyViz实例才能调用方法simpleprint

m = MyViz(simpledata)
m.simpleprint()

目前,您正在使用传递显式参数以将self绑定到MyViz.simpleprint ,但您传递的是DataFrame的实例,而不是MyViz 以下是合法的,尽管是非正统的:

m = MyViz(simpledata)
MyViz.simpleprint(m)

暂无
暂无

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

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