相关疑难解决方法(0)

Python中的类级别只读属性

有没有办法在Python中创建类级别的只读属性?例如,如果我有课Foo,我想说:

x = Foo.CLASS_PROPERTY
Run Code Online (Sandbox Code Playgroud)

但是阻止任何人说:

Foo.CLASS_PROPERTY = y
Run Code Online (Sandbox Code Playgroud)

编辑: 我喜欢Alex Martelli解决方案的简单性,但不喜欢它需要的语法.他和~ututbu的答案都启发了以下解决方案,这更接近我所寻找的精神:

class const_value (object):
    def __init__(self, value):
        self.__value = value

    def make_property(self):
        return property(lambda cls: self.__value)

class ROType(type):
    def __new__(mcl,classname,bases,classdict):
        class UniqeROType (mcl):
            pass

        for attr, value in classdict.items():
            if isinstance(value, const_value):
                setattr(UniqeROType, attr, value.make_property())
                classdict[attr] = value.make_property()

        return type.__new__(UniqeROType,classname,bases,classdict)

class Foo(object):
    __metaclass__=ROType
    BAR = const_value(1)
    BAZ = 2

class Bit(object):
    __metaclass__=ROType
    BOO = const_value(3)
    BAN = 4
Run Code Online (Sandbox Code Playgroud)

现在,我得到:

Foo.BAR …
Run Code Online (Sandbox Code Playgroud)

python

31
推荐指数
3
解决办法
1万
查看次数

在Python中,计算类中的变量数或阻止添加新的类变量

在python中,有没有办法防止在定义对象后添加新的类变量?

例如:

class foo:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

bar = foo()
try:
    bar.d = 4
except Exception, e:
    print "I want this to always print"
Run Code Online (Sandbox Code Playgroud)

或者,有没有办法计算对象中的变量数?

class foo:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3
    def count(self):
        ...

bar = foo()
if bar.count() == 3:
    print "I want this to always print"
Run Code Online (Sandbox Code Playgroud)

我想到这样做的唯一方法是使用字典或列表:

class foo:
    def __int__(self):
        self.dict = {'foo':1, 'bar':2} 
        self.len  = 2
    def chk():
        return self.len == …
Run Code Online (Sandbox Code Playgroud)

python variables class count

3
推荐指数
1
解决办法
3312
查看次数

标签 统计

python ×2

class ×1

count ×1

variables ×1