标签: class-attributes

Python DocString(Google 风格):如何记录类属性?

我有这个小例子:

"""Sandbox module"""

class Toto:
    """
    This class is an example

    Attributes:
        class_attribute (str): The class attribute #Unresolved reference
        instance_attribute (str): The instance attribute #OK
    """

    class_attribute = ""

    def __init__(self):
        self.instance_attribute = ""
        pass
Run Code Online (Sandbox Code Playgroud)

这会触发未解决的参考警告我应该如何正确记录类属性?

python docstring class-attributes python-sphinx

10
推荐指数
2
解决办法
1万
查看次数

python - 类属性显然不是继承的

在最近的一个项目中,我尝试做这样的事情(更复杂,但结果相同):

class MetaA(type):
    def __new__(cls, name, args, kwargs):
        print kwargs["foo"]
        return type.__new__(cls, name, args, kwargs)

class A(object):
    __metaclass__ = MetaA
    foo = "bar"

class B(A):
    pass
Run Code Online (Sandbox Code Playgroud)

我明白了:

bar
Traceback (most recent call last):
  File "C:\Users\Thorstein\Desktop\test.py", line 10, in <module>
    class B(A):
  File "C:\Users\Thorstein\Desktop\test.py", line 3, in __new__
    print kwargs["foo"]
KeyError: 'foo'
Run Code Online (Sandbox Code Playgroud)

类属性是否未继承?如果是这样,在与上述类似的框架中是否有可能的解决方法?

编辑:可能更容易看到我的意思使用程序中的实际(简化)示例..

class GameObjectMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs["dark_color"] = darken(*attrs["color"])
        return type.__new__(cls, name, bases, attrs)


class GameObject(object):
    __metaclass__ = GameObjectMeta
    color = (255,255,255)   # RGB tuple

class …
Run Code Online (Sandbox Code Playgroud)

python metaclass class-attributes

9
推荐指数
1
解决办法
2217
查看次数

真实世界使用自定义.NET属性

在现实世界中,您使用自定义.NET属性的是什么类型的东西?

我已经阅读了几篇关于它们的文章,但我从未使用过自定义属性.

我觉得当它们有用时我可能会忽略它们.

我在谈论您创建的属性,而不是已经包含在框架中的属性.

.net attributes custom-attributes class-attributes .net-attributes

8
推荐指数
2
解决办法
1594
查看次数

如何将SQLAlchemy与类属性(和属性)一起使用?

假设我正在制作带有物品的游戏(想想Minecraft,CS:GO武器,LoL和Dota物品等).游戏中可能存在大量相同的项目,但细节差异很小,例如条件/耐久性或项目中剩余的弹药数量:

player1.give_item(Sword(name='Sword', durability=50))
player2.give_item(Sword(name='Sword', durability=80))
player2.give_item(Pistol(name='Pistol', ammo=12))
Run Code Online (Sandbox Code Playgroud)

但是因为我不想每次都给我的剑和手枪命名(由于名字总是相同的),我希望它能够非常容易地创建新的项目类,我想我会name上课属性:

class Item:
    name = 'unnamed item'
Run Code Online (Sandbox Code Playgroud)

现在我只是将其子类化:

class Sword(Item):
    name = 'Sword'

    def __init__(self, durability=100):
        self.durability = durability

class Pistol(Item):
    name = 'Pistol'

    def __init__(self, ammo=10):
        self.ammo = ammo
Run Code Online (Sandbox Code Playgroud)

我们有工作班:

>>> sword = Sword(30)
>>> print(sword.name, sword.durability, sep=', ') 
Sword, 30
Run Code Online (Sandbox Code Playgroud)

但有没有办法以这种或那种方式使用SQLAlchemy 这些类属性(有时甚至是classproperties)?比如,我想将项目的持久性(实例属性)和名称(类属性)与其class_id(类属性)作为主键存储:

class Item:
    name = 'unnamed item'

    @ClassProperty  # see the classproperty link above
    def class_id(cls):
        return cls.__module__ + '.' + cls.__qualname__

class Sword(Item): …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy properties class-attributes python-3.x

8
推荐指数
1
解决办法
2635
查看次数

弃用 django 模型中的字段

我正在标准化与 Django 项目关联的数据库,并将字段移动到不同的表。作为实现过程的一部分,如果我的同事在添加新表后在我实际删除列之前尝试使用旧属性,我想向他们发出弃用警告。

class Asset(Model):
    model = models.CharField(max_length=64, blank=True, null=True)
    part_number = models.CharField(max_length=32, blank=True, null=True) # this will be a redundant column to be deprecated
    company = models.ForeignKey('Company', models.CASCADE, blank=True, null=True) # this will be a redundant column to be deprecated
    # other database fields as attributes and class methods
Run Code Online (Sandbox Code Playgroud)

warnings.warn('<field name> is deprecated', DeprecationWarning)我的理解是,我需要在课堂上的某个地方添加一些内容,但是我会在哪里添加它呢?

django django-models class-attributes python-3.x deprecation-warning

8
推荐指数
2
解决办法
6859
查看次数

如何教SpecFlow向我的测试类添加额外的NUnit属性

SpecFlow非常棒 - 它非常有助于我们进行适当的集成测试.

我想知道的一件事是,是否有办法告诉SpecFlow将其他NUnit属性添加到它在功能代码隐藏文件中创建的测试类中.

现在,我的测试类生成如下:

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Some action description here")]
public partial class MySampleFeature
{  
   ......
}
Run Code Online (Sandbox Code Playgroud)

在SpecFlow中是否有任何方法告诉它添加额外的NUnit属性来定义测试的类别 - 如下所示:

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Some action description here")]
[NUnit.Framework.Category("LongRunningTests")]   <== add this "Category" attribute
public partial class MySampleFeature
{  
   ......
}
Run Code Online (Sandbox Code Playgroud)

手动将其添加到生成的代码隐藏是浪费 - 下次SpecFlow重新生成代码隐藏时,我必须记住再次执行它(很可能,我会忘记).

如果SpecFlow中还没有这种能力 - 如何申请加入?:-)

nunit class-attributes specflow

7
推荐指数
1
解决办法
6064
查看次数

如何使用jquery检查多个元素是否具有相同的类?

是否可以缩小此选择器?

if ($("#element1").hasClass("highlight") && $("#element2").hasClass("highlight") && $("#element3").hasClass("highlight") && $("#element4").hasClass("highlight") && $("#element5").hasClass("highlight")) {
  $("#newstyle).css("visibility", "visible");
};
Run Code Online (Sandbox Code Playgroud)

我已经试过了

if ($("#element1, #element2, #element3, #element4, #element5").hasClass("highlight"))
Run Code Online (Sandbox Code Playgroud)

if ($("#element1 && #element2 && #element3 && #element4 && #element5").hasClass("highlight"))
Run Code Online (Sandbox Code Playgroud)

......但这是不正确的.

基本上我有很多像这样的条件:5个指定的元素hasClass XYZ.所以我很感激压缩它.

html javascript jquery jquery-selectors class-attributes

6
推荐指数
1
解决办法
1338
查看次数

Python:类属性的继承(列表)

继承超类的类属性,稍后更改子类的值可以正常工作:

class Unit(object):
    value = 10

class Archer(Unit):
    pass

print Unit.value
print Archer.value

Archer.value = 5

print Unit.value
print Archer.value
Run Code Online (Sandbox Code Playgroud)

导致输出:
10
10
10
5
这很好:Archer继承了Unit的值,但是当我改变Archer的值时,Unit的值保持不变.

现在,如果继承的值是列表,则浅拷贝效果会发生,并且超类的值也会受到影响:

class Unit(object):
    listvalue = [10]

class Archer(Unit):
    pass

print Unit.listvalue
print Archer.listvalue

Archer.listvalue[0] = 5

print Unit.listvalue
print Archer.listvalue
Run Code Online (Sandbox Code Playgroud)

产量:
10
10
5
5

从超类继承列表时,有没有办法"深度复制"列表?

非常感
谢佐诺

python inheritance list deep-copy class-attributes

5
推荐指数
2
解决办法
1万
查看次数

属性更改时更新Ruby类属性哈希

我正在尝试编写一个类似于Rails AactiveRecord模型的Ruby类,其处理方式是:

class Person
  attr_accessor :name, :age

  # init with Person.new(:name => 'John', :age => 30)
  def initialize(attributes={})
    attributes.each { |key, val| send("#{key}=", val) if respond_to?("#{key}=") }
    @attributes = attributes
  end

  # read attributes
  def attributes
    @attributes
  end

  # update attributes
  def attributes=(attributes)
    attributes.each do |key, val| 
      if respond_to?("#{key}=")
        send("#{key}=", val) 
        @attributes[key] = name
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我的意思是,当我初始化类时,使用相关属性更新"属性"哈希:

>>> p = Person.new(:name => 'John', :age => 30)
>>> p.attributes
 => {:age=>30, :name=>"John"}
>>> p.attributes = { :name => 'charles' …
Run Code Online (Sandbox Code Playgroud)

ruby abstract-class metaprogramming class-attributes

5
推荐指数
1
解决办法
6049
查看次数

如何从类属性中删除与模式匹配的类,但保留其他类?

我想从所有标签上的class属性中删除以"blue"结尾的类

示例HTML

<p class="text_blue happy">this is blue text</p>
<p class="text_red nothappy">this is red text</p>
<img class="img_blue nothappy" />
Run Code Online (Sandbox Code Playgroud)

这将为我提供所有以'blue'结尾的类的元素

$('[class$=blue]');
Run Code Online (Sandbox Code Playgroud)

如何从class属性中弹出这些匹配的类名?

jquery jquery-selectors class-attributes

5
推荐指数
1
解决办法
4851
查看次数