我需要一个整数类,它的值可以在创建对象后更改.我需要这个类来定义一个首先以毫米为单位指定的大小.稍后在创建用户界面时,我从设备上下文中获取一个因子,将毫米转换为像素.此因子应将我的对象的毫米值更改为像素值.
我试图将int子类化(参见increment int object),但int是不可变的,因此我无法更改其值.
class UiSize(int):
def __new__(cls, value=0):
i = int.__new__(cls, value)
i._orig_value = value
return i
def set_px_per_mm(self, px_per_mm):
pixel_value = int(round(self._orig_value * px_per_mm))
print "pixel_value", pixel_value
# how to set the new pixel_value to the object's value ?
s = UiSize(500)
s.set_px_per_mm(300.0 / 500.0)
print "1px + 500mm =", 1 + s, "px" # the result should be 301 pixels
Run Code Online (Sandbox Code Playgroud)
增量int对象的答案是用所有int的方法构建我自己的类.所以我尝试了这个:
class UiSize2(object):
def __init__(self, value=0):
self._int_value = int(value)
def __add__(self, other):
return self._int_value.__add__(other) …Run Code Online (Sandbox Code Playgroud) 我有一段带有双向链表的代码(受linux列表的启发),无需编译器优化即可工作。当我激活编译器优化时,它失败了。
我的程序将一个元素添加到列表中,然后在列表不为空时循环遍历列表。在循环体中,获取第一个元素,然后断言检查该元素是否在列表中,然后删除该元素。此断言因编译器优化而失败 ( -O2)。有了编译器障碍,就不会有错误。
我假设在错误情况下,编译器不会在每次循环迭代中重新加载列表的元素while (!list_empty(&li))。当我查看主函数的编译代码时,我发现没有条件代码,并且__assert_fail在最后被调用。但为什么?我一直认为在单线程代码中编程是安全的,没有障碍。
这是我的代码:
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <assert.h>
struct list_elem {
struct list_elem *next;
struct list_elem *prev;
};
struct list {
struct list_elem *next;
struct list_elem *prev;
};
static inline void init_list_head(struct list *list)
{
list->next = (struct list_elem *)list;
list->prev = (struct list_elem *)list;
}
static inline void init_list_elem(struct list_elem *elem)
{
elem->next = NULL;
elem->prev = NULL;
}
static inline void *list_entry(struct list_elem *elem, size_t offset) …Run Code Online (Sandbox Code Playgroud)