Fields in python

本文通过一个Python类实例解释了为什么在某些情况下需要创建新的字段而非直接使用类中的现有字段。这涉及到Python中类字段的作用域问题,并对比了Java等其他语言的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Quesion Description

While reading scikit source code, got confused by following codes in line 149, 150 in classification.py under scikit-learn-0.15.2\sklearn\neighbors in scikit-learn-0.15.2.

classes_ = self.classes_
_y = self._y

Where classes_ is the classes of iris and _y is the sample’s targets.

Why create new fields instead of using them directly?

Explain

The reason is about that scope.

Here is an example to show this.

class A:
    'test fields in Python'       
    def __init__(self, a=3):
        self.a = a
        print self.a        

    def f(self, b):
        a = self.a + b
        print a
        return a, self.a, b

    def p(self):
        print self.a


aa = A(10)
c, _, d = aa.f(3)
aa.p()
print c, d 

The output is

10

13

10

13, 3

Unlike java, in python, fields in a class are not available in methonds in the same class. So if you want to use them, use self and create new fields in methods.

By the way, we can use _ to ignore return values that we don’t want. This idea is from pridict function:

mode, _ = stats.mode(_y[neigh_ind, k], axis=1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值