Cli*_*ley 3 python scope function
我不认为这是因为该功能的范围,但我得到一个
尚未解析的引用,位于get_all_predicates(examples).count(predicate_list [0])
get_entropy_of_attributes(examples, predicate_list)我班上的内部函数Tree:
class Tree:
def get_examples(examples, attributes):
for value in examples:
yield dict(zip(attributes, value.strip().replace(" ", "").split(',')))
def get_all_predicates(examples):
return [d['Predicate'] for d in examples]
def get_entropy_of_attributes(examples, predicate_list):
get_all_predicates(examples).count(predicate_list[0])
return 0
examples = list(get_examples(all_examples, name_of_attributes))
predicate_list = list(set(get_all_predicates(examples)))
get_entropy_of_attributes(examples, predicate_list)
Run Code Online (Sandbox Code Playgroud)
all_examples是词典name_of_attributes列表,并且是列表,其中包含从文本文件导入的值。
all_examples = [{'P_Length': '1.4', 'P_Width': '0.2', 'Predicate': 'I-setosa', 'Sepal_Width': '3.5', 'S_Length': '5.1'}, ...]
name_of_attributes = ["Check","P-Width"]
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
如果你想调用类方法,你必须用 来调用它们self,例如
class myClass:
def __init__(self):
pass
def get_all_predicates(self):
print('asd')
def do_something(self):
self.get_all_predicates() # working
get_all_predicates() # ? Unresolved reference
test = myClass()
test.do_something()
Run Code Online (Sandbox Code Playgroud)
有关Python 类的示例,请参阅此链接。
类没有作用域,只有名称空间。这意味着在其中定义的函数无法自动查看其他类变量。
class Foo(object):
var = 1 # lets create a class variable
def foo():
print(var) # this doesn't work!
Run Code Online (Sandbox Code Playgroud)
要访问类变量,您需要使用属性语法:(Foo.var通过类访问),或者(如果您正在编写实例方法)使用self.var(通过当前实例访问,这将作为第一个参数传递) 。
class Bar(object):
var = 1
def bar1():
print(Bar.var) # works
def bar2(self):
print(self.var) # also works, if called on an instance, e.g. `Bar().bar2()`
Run Code Online (Sandbox Code Playgroud)
通过这种设置,您几乎可以修复当前代码(但不能完全解决)。
def get_entropy_of_attributes(examples, predicate_list):
Tree.get_all_predicates(examples).count(predicate_list[0]) # name the class
return 0
Run Code Online (Sandbox Code Playgroud)
如果在类完全初始化后调用此函数,它将在没有任何异常的情况下正常工作(尽管其实现似乎有点荒谬)。但是,当您调用它来定义类变量时,它不起作用,就像您当前的代码一样。这是因为仅在运行所有类主体之后,才创建类对象并将其绑定到类名称。
我认为解决此问题的方法可能是以更常规的方式重新设计您的课程。可能不是通过基于各种全局变量(例如all_examples)来设置类变量,而是应该通过将参数传递给构造函数并使从其计算出的其他变量成为实例属性来创建类的实例。我会尽力将其写出来,但坦率地说,我不明白您的状况如何。