If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.
class A:
# do something
def some_func(self, a: 'A')
# ...
See ref below
- https://github.com/python/mypy/issues/3661
- https://www.youtube.com/watch?v=AJsrxBkV3kc
If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.
class A:
# do something
def some_func(self, a: 'A')
# ...
See ref below
- https://github.com/python/mypy/issues/3661
- https://www.youtube.com/watch?v=AJsrxBkV3kc
In Python you cannot reference the class in the class body, although in languages like Ruby you can do it.
In Python instead you can use a class decorator but that will be called once the class has initialized. Another way could be to use metaclass but it depends on what you are trying to achieve.
How to reference the class itself in python - Stack Overflow
How to reference class variables inside class method
How to reference a class variable in python - Stack Overflow
Composition - Reference to another class in Python - Stack Overflow
You need @classmethod rather than @staticmethod - a class method will get passed a reference to the class (where a method will get self), so you can look up attributes on it.
class FooBarBaz:
BAR = 123
@classmethod
def getBar(cls):
return cls.BAR
Actually, there is __class__ in python 3:
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... @staticmethod
... def foo():
... print(__class__)
...
>>> A.foo()
<class '__main__.A'>
>>>
See http://www.python.org/dev/peps/pep-3135 for the rationale why it has been added.
No idea about how to achieve the same in py2, I guess this is not possible.
class Test:
config: Dict[str, str]
parameters: Dict[str, str]
def default(cls)
return cls(
parameters=get_params(),
config=get_config(file="ATTRIBUTE FROM PARAMETERS"
)
# I tried it like this:
class Test:
config: Dict[str, str]
parameters: Dict[str, str]
def default(cls)
return cls(
parameters=get_params(),
config=get_config(file=cls.parameters.config_file)
)
# AttributeError: type object 'Test' has no attribute 'parameters'You need to store a reference to the object which has the instance of a Y object:
class X(object):
def __init__(self):
self.count = 5
self.y = Y(self) #create a y passing in the current instance of x
def add2(self):
self.count += 2
class Y(object):
def __init__(self,parent):
self.parent = parent #set the parent attribute to a reference to the X which has it
def modify(self):
self.parent.add2()
Example usage:
>>> x = X()
>>> x.y.modify()
>>> x.count
7
Maybe it's possible for you to use class inheritance? For example:
class X(object):
def __init__(self):
self.count = 5
def add2(self):
self.count += 2
class Y(X):
def __init__(self):
super(Y, self).__init__()
def modify(self):
self.add2()
y = Y() # We now create an instance of Y which is a child class of 'super' class X
y.modify()
print(y.count) # 7
You could also make it work by adding a wrapper class that is smarter about what calling whatever it's dealing with.
Since you mentioned in a comment that you're going to need to make the call to one of thewritersmultiple places, I've updated my answer to address this by adding a nested wrapper class to encapsulate the logic of calling the various callable types in one spot. This is a classic example of using OOP to apply the DRY principle.
def save_c(v):
print("c :" + v)
class Writer(object):
@classmethod
def save(cls, t, v):
cls.writerst
@classmethod
def save_a(cls, v):
print("a :" + v)
@staticmethod
def save_b(v):
print("b :" + v)
def _wrapper(writer):
if isinstance(writer, classmethod):
return type('ClassmethodWrapper', (object,), {'__call__':
lambda self, cls, v: writer.__func__(cls, str(v))})()
elif isinstance(writer, staticmethod):
return type('StaticmethodWrapper', (object,), {'__call__':
lambda self, cls, v: writer.__func__(str(v))})()
else:
return type('VanillaWrapper', (object,), {'__call__':
lambda self, cls, v: writer(str(v))})()
writers = list(map(_wrapper, (save_a, save_b, save_c)))
if __name__ == "__main__":
Writer.save(0, [1, 2, 3]) # -> a :[1, 2, 3]
Writer.save(1, [4, 5, 6]) # -> b :[4, 5, 6]
Writer.save(2, [7, 8, 9]) # -> c :[7, 8, 9]
It sounds like you meant to use @staticmethod rather than @classmethod.
For more information, see What is the difference between @staticmethod and @classmethod in Python?
That reference isn't describing a special case of the language rules, it's a natural result of everything being an object.
The special case is that MyClass(args...) is wired up to create a new object and call MyClass.__init__ (among other things).
It allows you to change the state of the class after it is defined. This can be as simple as changing "static" data based on some configuration.
class EggsApiClient:
default_url = "example.com"
def connect(self):
# do stuff with default_url
if __name__ = "main":
EggsApiClient.default_url = parse_args("default_url")
This is not something that I think most Python users will ever need to do and almost surely shouldn't but it does have a distinct purpose and it's worth understanding.
Consider the following example:
class Foo:
def set_a(self, a):
self.a = a
class Bar:
def set_b(self, b):
self.b = b
foo = Foo()
foo.set_a(1)
print(foo.a)
bar = Bar()
# interesting part here!
Foo.set_a(bar, 2)
print(bar.a)
Through this feature, we have effectively called set_a on a Bar instance, despite the fact that Bar doesn't have a set_a method defined. That is, if we try:
bar.set_a()
We get an error: AttributeError: 'Bar' object has no attribute 'set_a'.
You might (quite reasonably) ask, "OK, but why would I do that?" Personally, I think I did something like this many moons ago but there was probably a simpler solution to whatever I was trying to accomplish.
I can imagine this be useful in various frameworks e.g. something like unit testing. But the main reason I think you might end up doing this is when you are using a more functional style. For example, you might have a function like this which has no knowledge of Foo or Bar:
def apply(obj, func, *params):
func(obj, *params)
Which you can then call like so:
apply(bar, Bar.set_b, 3)
print(bar.b)
A real example of the kind of thing you might actually do:
class Person:
def __init__(self, name: str, student: bool):
self.name = name
self.student = student
def is_student(self):
return self.student
def __repr__(self):
return f"{self.name} - student: {self.student}"
people = [Person("bob", False), Person("alice", True), Person("carl", True)]
def display(iter):
print("---")
for i in iter:
print(i)
display(people)
display(filter(Person.is_student, people))
Or maybe something like this:
people = map(Person, ["dave", "edith", "frank"], [True, False, True])
display(people)
Check out the functools module for more interesting functional-style approaches like this.
In the clas body, you're creating the class; there is no self, so you obviously cannot yet refer to self.anything. But also within that body there is as yet no a: name a gets bound AFTER the class body is done. So, although that's a tad less obvious, in the body of class a you cannot refer to a.anything either, yet.
What you CAN refer to are bare names of class attributes that have already been bound: for example, you could simply use 5, spam] at the end of your list lut. spam will be there as a function, as you say at one point that you want; not as a method, and most definitely NOT as a class method (I don't see classmethod ANYWHERE in your code, why do you think a class method would magically spring into existence unless you explicitly wrap a function in the classmethod builtin, directly or by decorator?) -- I suspect your use of "class method" does not actually refer to the class-method type (though it's certainly confusing;-).
So, if you later need to call that function on some instance x of a, you'll be calling e.g. a.lut-1, with the argument explicitly there.
If you need to do something subtler it may be possible to get a bound or unbound method of some sort at various points during processing (after the class creation is done, or, if you want a bound instance method, only after a specific instance is instantiated). But you don't explain clearly and completely enough what exactly it is that you want to do, for us to offer very detailed help on this later-stage alternatives.
While you are in the scope of the class, you can just write
class A:
def spam(self):
pass
lut = [1, 2, 3, spam]
a = A()
print a.lut
gives
[1, 2, 3, <function spam at 0xb7bb764c>]
Don't forget that this is a function in your lookup table, not a number as you probably intended. You probably want to solve another problem.