没有类的属性方法 [英] Property method without class

查看:62
本文介绍了没有类的属性方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码

global_variable = 1

@property
def method():
    # Some magic, for example 
    # incrementing global variable
    global global_variable
    global_variable += 1
    return global_variable

print method

此代码返回

<property object at 0x28dedb8>

但是我希望2。在Python中是否可以在类外使用属性装饰器?

But I expect 2. Is it possible in python to use property decorator outside a class?

推荐答案

@properties 应该是 instance 属性,在类中定义。例如:

@properties are meant to be instance properties, defined in a class. E.g.:

class A(object):
   @property
   def a(self):
      return 2

b = A()
b.a
=> 2

如果我理解,您正在尝试定义模块属性(或全局属性) )。没有简单/干净的方法可以做到这一点。请参阅此相关问题

If I understand, you're trying to define a module-property (or "global" property). There's no easy/clean way to do that. See this related question.

编辑:您还可以定义 classproperty ,使您的媒体资源更具全球性(不需要实例) )。 classproperty 不是内置的,但易于定义。这是定义它的一种方法:

you can also define a classproperty, to make your property more global-like (does not required an instance). classproperty is not a built in, but is easy to define. Here's one way to define it:

class classproperty(object):
    def __init__(self, f):
        self.f = classmethod(f)
    def __get__(self, *a):
        return self.f.__get__(*a)()

现在您可以这样做:

class A(object):
   @classproperty
   def a(self):
      return 2

A.a
=> 2

这篇关于没有类的属性方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆