我正在Python中创建一些自定义类,我想知道是否有任何方法可以在类上定义一个属性,而不让它的所有实例继承该属性。
例如:
class Foo():
def bar():
pass
Foo.bar # would return `bar` function
instanceOfFoo = Foo()
instanceOfFoo.bar # would raise an AttributeError
我知道我可以子类Foo,重写bar,并手动将AttributeError作为@property来提供bar不存在的“外观”,但是没有子类有什么方法可以做到这一点呢?
上下文
简单地说,Python描述了获取属性时的查找过程。这本书区分了两个案例
从类(例如cls.name )获取属性时的查找过程
从类获取属性
当您使用语法C.name来引用类对象C上的属性时,查找分两个步骤进行:
1. When `name` is a key in `C.__dict__`, `C.name` fetches the value `v` from `C.__dict__['name']` . Then, when `v` is a descriptor (i.e., `type(v)` suppl
在Python中,我可以使用@classmethod装饰器创建一个类方法:
>>> class C:
... @classmethod
... def f(cls):
... print(f'f called with cls={cls}')
...
>>> C.f()
f called with cls=<class '__main__.C'>
或者,我可以在元类上使用一个普通(实例)方法:
>>> class M(type):
... def f
关于运行以下代码的行为,我有两个问题。为什么在没有实例化对象的情况下调用__new__?我认为__new__控制了一个新实例的创建。接下来,为什么当AttributeError返回True的大小时,hasattr会引发
class ShapeBase(type):
def __new__(cls, name, bases, attrs):
rv = super(ShapeBase, cls).__new__(cls, name, bases, attrs)
parents = [base for base in bases if isinstance(base, Shap
我正在使用类和子类作为应用程序工作。对于每个类,包括超级类和子类,都有一个名为label的类变量。我希望超类的label变量默认为类名。例如:
class Super():
label = 'Super'
class Sub(Super):
label = 'Sub'
与手工为每个类键入变量不同,是否可以从超类中的类名派生变量并为子类自动填充变量?
class Super():
label = # Code to get class name
class Sub(Super)
pass
# When inherited
它是Django deb模型的简化重新实现。 这是可行的(类似于Django所做的,尽管它是一个属性,而不是一个属性): class ClassPropertyType(type):
@property
def objects(cls):
return cls.init_empty_storage_if_needed()
class Model(metaclass=ClassPropertyType):
@classmethod
def init_empty_storage_if_needed(cls):
if not ha
我想在python中实现单例模式,我喜欢中描述的模式。
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class SingletonClass(metaclass=S
在Python中工作,如何通过它实例化的类检索元类(元方法)所拥有的方法?在下面的场景中,这很简单--只需使用getattr或点符号:
*所有示例都使用版本安全的
class A(type):
class A(type):
"""a metaclass"""
def method(cls):
m = "this is a metamethod of '%s'"
print(m % cls.__name__)
class B(with_metacla
这不起作用:
def register_method(name=None):
def decorator(method):
# The next line assumes the decorated method is bound (which of course it isn't at this point)
cls = method.im_class
cls.my_attr = 'FOO BAR'
def wrapper(*args, **kwargs):
method(
我正在编写一个用于与dataset交互的包,其代码如下所示
from abc import ABC, ABCMeta, abstractmethod
from functools import cache
from pathlib import Path
from warnings import warn
class DatasetMetaClass(ABCMeta):
r"""Meta Class for Datasets"""
@property
@cache
def metaclass_property
我在玩Groovy,我想知道,为什么这段代码不能工作?
package test
interface A {
void myMethod()
}
class B implements A {
void myMethod() {
println "No catch"
}
}
B.metaClass.myMethod = {
println "Catch!"
}
(new B()).myMethod()
它打印No catch,而我希望它打印Catch!。