我想在我的 Python 程序中使用 Decimal 类进行财务计算。小数不能与浮点数一起使用 - 它们需要首先显式转换为字符串。因此,我决定对 Decimal 进行子类化,以便能够在无需显式转换的情况下使用浮点数。
m_Decimal.py:
# -*- coding: utf-8 -*-
import decimal
Decimal = decimal.Decimal
def floatCheck ( obj ) : # usually Decimal does not work with floats
return repr ( obj ) if isinstance ( obj, float ) else obj # this automatically converts floats to Decimal
class m_Decimal ( Decimal ) :
__integral = Decimal ( 1 )
def __new__ ( cls, value = 0 ) :
return Decimal.__new__ ( cls, floatCheck …Run Code Online (Sandbox Code Playgroud) 我为我的网站制作了一组按钮,我需要一些专业的见解.
为了减少CSS膨胀,我想将我的按钮子类化为不同的颜色,ex .button.blue.
将来会出现以下问题吗?(假设我没有制作.blue的类)我是否必须使用像.button.button-blue这样的东西?
.button {
display:inline-block;
padding: 9px 18px;
margin: 20px;
text-decoration: none;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
text-align: center;
background: #FFE150;
}
.button.blue {
background: #49b8e7;
border:1px solid #54abcf;
border-bottom:1px solid #398fb4;
color:#FFF
text-shadow: 0 1px 0 rgba(255,255,255, 0.5);
}
.header{
height: 50px;
}
.header.blue {
background: blue;
color: #fff;
}
Run Code Online (Sandbox Code Playgroud) 在基本上处理自定义枚举类型实现时,我遇到了这样一种情况:我必须从两者中派生出单独但几乎相同的子类int,long因为它们是Python中的不同类.这似乎有点讽刺意味,因为两者的实例通常可以互换使用,因为大多数情况下它们只是在需要时自动创建.
我的工作很好,但本着DRY(不要重复自己)的精神,我不禁想知道是否有更好的,或者至少更简洁的方式来实现这一点.目标是让子类实例可以在任何地方使用 - 或尽可能接近 - 它们的基类实例可以使用.理想情况下,这应该自动发生,类似于内置int()实际返回的方式,long只要它检测到一个是必需的.
这是我目前的实施:
class NamedInt(int):
"""Subclass of type int with a name attribute"""
__slots__ = "_name" # also prevents additional attributes from being added
def __setattr__(self, name, value):
if hasattr(self, name):
raise AttributeError(
"'NamedInt' object attribute %r is read-only" % name)
else:
raise AttributeError(
"Cannot add attribute %r to 'NamedInt' object" % name)
def __new__(cls, name, value):
self = super(NamedInt, NamedInt).__new__(cls, value)
# avoid call to …Run Code Online (Sandbox Code Playgroud) 首先,我知道之前已经提出了类似的问题,并且我尝试遵循此 stackoverflow答案的建议,但无济于事.我也尝试添加这个的基本要点作为评论,但我还没有足够的代表:(基本上我试图使用PFSubclassing来扩展Parse的PFUser模型.因此,这是我的相应代码:
User.swift:
import Foundation
import CoreLocation
class User : PFUser, PFSubclassing {
override init() {
super.init()
}
convenience init(email: String!) {
self.init()
self.email = email
self.username = email
}
// don't need to call User.registerSubclass() in AppDelegate because this
// is handling that here
override class func load() {
self.registerSubclass()
}
// Commented out because this is extending PFUser
// override class func parseClassName() -> String! {
// return "PFUser"
// }
}
Run Code Online (Sandbox Code Playgroud)
测试结果:
-[PFObject _loadSensitiveUserDataFromKeychainItemWithName:]: unrecognized selector …Run Code Online (Sandbox Code Playgroud) 我正在将C模块中定义的类型子类化为别名的一些属性和方法,以便我的脚本在不同的上下文中工作.
如何让它工作,我必须手动调整我班级的字典?如果我没有DistanceTo在dictionnary中添加引用,我会得到Point3d has no attribute named DistanceTo.
class Point3d(App.Base.Vector):
def __new__(cls, x, y, z):
obj = super(Point3d, cls).__new__(cls)
obj.x, obj.y, obj.z = x, y, z
obj.__dict__.update({
'X':property(lambda self: self.x),
'Y':property(lambda self: self.y),
'Z':property(lambda self: self.z),
'DistanceTo':lambda self, p: self.distanceToPoint(p)})
return obj
def DistanceTo(self, p): return self.distanceToPoint(p)
Run Code Online (Sandbox Code Playgroud)
我在想,一旦__new__返回了一个实例,我仍然可以用方法和属性填充它.任何人都可以对此有所了解吗?
编辑:我导入的模块是FreeCAD.那里定义了C基类型.然后Vector是衍生形式这个定义在这里
编辑2:我也尝试了以下内容:
class Point3d(App.Base.Vector):
def __new__(cls, x, y, z):
obj = super(Point3d, cls).__new__(cls)
obj.x, obj.y, obj.z = x, y, z
obj.__dict__.update({
'X': x, 'Y': …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我阅读了EKEvent类型的日历事件,并且我已经使用大量计算变量进行了扩展,因此我可以轻松获得日历中每个事件的持续时间,工时等数量.但是在大规模中,性能很差 - 所以我想使用lazy vars来缓存我所有的额外数据.
因此,我想创建一个EKEvent的子类 - 名为CustomEvent,它添加了懒惰的变量,但我的问题是EKEventStore总是返回EKEvents,我需要将它转换为我的CustomEvent子类的实例,以便能够访问懒惰的vars等
一个简单的类型转换是不够的,我已经在操场上试过,看看哪些可行,但没有任何用处.我需要一个CustomRectangle的特殊构造函数,它可以从NativeRectangle初始化一个CustomRectangle.另一种解决方案是创建一个包装类,将原始对象保存为属性,但这不是我最喜欢的解决方案,因为我必须映射所有方法和属性
class NativeRectangle: NSObject {
var width: Int
var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
super.init()
}
}
class CustomRectangle: NativeRectangle {
var area: Int { return width * height}
}
let rect = NativeRectangle(width: 100, height: 20)
let customRect = CustomRectangle(rect) // This fails, i need a constructor
print(customRect.area)
Run Code Online (Sandbox Code Playgroud) 考虑以下:
class MyElem extends HTMLElement {};
customElements.define('my-element', MyElem);
class MyMoreSpecificElem extends MyElem {};
customElements.define('my-more-specific-element', MyMoreSpecificElem);
Run Code Online (Sandbox Code Playgroud)
在对象继承的说法中,第二个类的实例与第一个类具有“is-a”关系: aMyMoreSpecificElem 是 a MyElem。
这种关系在 JavaScript 中被捕获:
let subclassInstance = document.querySelector('my-more-specific-element');
let parentClass = document.querySelector('my-element').constructor;
subclassInstance instanceof parentClass; // true
Run Code Online (Sandbox Code Playgroud)
但是我想不出任何MyElem使用 CSS 选择器选择所有s(包括子类 MyMoreSpecificElem)的方法。标签选择器只会获得超类或子类,我知道的所有关系描述选择器(例如~、>)都是关于文档中的位置,而不是类层次结构。
我的意思是,当然,我可以在构造函数中添加一个 CSS 类并通过它进行选择,调用super将确保甚至可以以这种方式选择子类实例。但这很粗糙。有没有办法在纯 CSS 中做到这一点?
为简单起见,让我们从 numpy 文档中复制诊断 ndarray 子类:
import numpy as np
class MySubClass(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
print('In __array_finalize__:')
print(' self is %s' % repr(self))
print(' obj is %s' % repr(obj))
if obj is None: return
self.info = getattr(obj, 'info', None)
Run Code Online (Sandbox Code Playgroud)
现在让我们做一个简单的例子:
>>> x = MySubClass(np.ones((1,5)))
In __array_finalize__:
self is MySubClass([[1., 1., 1., 1., 1.]])
obj is array([[1., 1., 1., 1., 1.]])
>>> y = x.T
In __array_finalize__:
self is MySubClass([[1., …Run Code Online (Sandbox Code Playgroud) 我有一个协议,我为其分配了一些默认值:
protocol HigherProtocol {
var level: Int { get }
func doSomething()
}
extension HigherProtocol {
var level: Int { 10 }
func doSomething() {
print("Higher level is \(level)")
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个协议,它符合更高级别的协议,但具有不同的默认值和函数实现:
protocol LowerProtocol: HigherProtocol {}
extension LowerProtocol {
var level: Int { 1 }
func doSomething() {
print("Lower level is \(level)")
}
}
Run Code Online (Sandbox Code Playgroud)
然后我创建一个符合 HigherProtocol 的类,然后创建一个符合较低级别协议的子类:
class HigherClass: HigherProtocol {}
class LowerClass: HigherClass, LowerProtocol {}
Run Code Online (Sandbox Code Playgroud)
然而,当我实例化这个较低的类时,它显示了一些奇怪的行为:
let lowerClass = LowerClass()
lowerClass.level // is 1
lowerClass.doSomething() // Prints "Lower level …Run Code Online (Sandbox Code Playgroud) subclassing ×10
python ×4
swift ×3
css ×2
ios ×2
c++ ×1
casting ×1
css-cascade ×1
decimal ×1
eventkit ×1
freecad ×1
javascript ×1
numpy ×1
python-c-api ×1
qt ×1