Questions tagged [class-method]
Methods that are called on a class instead of on an object.
class-method
917
questions
4681
votes
36
answers
1.1m
views
What is the difference between @staticmethod and @classmethod in Python?
What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
1940
votes
12
answers
848k
views
Meaning of @classmethod and @staticmethod for beginner [duplicate]
What do @classmethod and @staticmethod mean in Python, and how are they different? When should I use them, why should I use them, and how should I use them?
As far as I understand, @classmethod tells ...
464
votes
18
answers
342k
views
What is the difference between class and instance methods?
What's the difference between a class method and an instance method?
Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?
404
votes
9
answers
248k
views
Ruby: Calling class method from instance
In Ruby, how do you call a class method from one of that class's instances? Say I have
class Truck
def self.default_make
# Class method.
"mac"
end
def initialize
# Instance method.
...
295
votes
18
answers
159k
views
What is the purpose of class methods?
I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use ...
227
votes
9
answers
312k
views
How to make a class property? [duplicate]
In python I can add a method to a class with the @classmethod decorator. Is there a similar decorator to add a property to a class? I can better show what I'm talking about.
class Example(object):
...
136
votes
3
answers
59k
views
When should I use @classmethod and when def method(self)?
While integrating a Django app I have not used before, I found two different ways to define functions inside the class. The author seems to use them both distinctively and intentionally. The first one ...
131
votes
4
answers
59k
views
Calling a base class's classmethod in Python
Consider the following code:
class Base(object):
@classmethod
def do(cls, a):
print cls, a
class Derived(Base):
@classmethod
def do(cls, a):
print 'In derived!'
...
119
votes
6
answers
54k
views
How do I use define_method to create class methods?
This is useful if you are trying to create class methods metaprogramatically:
def self.create_methods(method_name)
# To create instance methods:
define_method method_name do
...
end
...
103
votes
5
answers
83k
views
Using super with a class method
I'm trying to learn the super() function in Python.
I thought I had a grasp of it until I came over this example (2.6) and found myself stuck.
http://www.cafepy.com/article/...
86
votes
7
answers
49k
views
What's an example use case for a Python classmethod?
I've read What are Class methods in Python for? but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python.
...
81
votes
3
answers
5k
views
Should constructors comply with the Liskov Substitution Principle? [closed]
I usually try to make sure my object instances comply with the Liskov Substitution Principle, but I've always wondered is do people think LSP should apply to constructors too?
I've tried googling for ...
79
votes
5
answers
44k
views
__getattr__ for static/class variables
I have a class like:
class MyClass:
Foo = 1
Bar = 2
Whenever MyClass.Foo or MyClass.Bar is invoked, I need a custom method to be invoked before the value is returned. Is it possible in ...
79
votes
11
answers
29k
views
Attaching a decorator to all functions within a class
Is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function?
I suppose it then becomes a kind of aspect, rather than a ...
66
votes
5
answers
18k
views
How to understand the difference between class_eval() and instance_eval()?
Foo = Class.new
Foo.class_eval do
def class_bar
"class_bar"
end
end
Foo.instance_eval do
def instance_bar
"instance_bar"
end
end
Foo.class_bar #=> undefined method ‘class_bar’ ...
53
votes
2
answers
17k
views
ActiveRecord Rails 3 scope vs class method
I'm new to the new query interface of ActiveRecord so I'm still figuring things out.
I was hoping someone could explain the difference between using a scope in an ActiveRecord model and just using ...
53
votes
7
answers
33k
views
Is it bad form to call a classmethod as a method from an instance?
Ex.
If I have something like this:
class C(object):
@classmethod
def f(cls, x):
return x + x
This will work:
c = C()
c.f(2)
4
But is that bad form?
Should I only call
C.f()
or
...
52
votes
6
answers
96k
views
Can you use a string to instantiate a class?
I'm using a Builder pattern in Python to separate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named ID... (e.g. ID12345). These all inherit from the ...
49
votes
3
answers
47k
views
Python - how can I get the class name from within a class method - using @classmethod
I have the following code:
class ObjectOne(object):
@classmethod
def print_class_name(cls):
print cls.__class__.__name__
def print_class_name_again(self):
print self....
36
votes
3
answers
21k
views
How to dynamically define a class method which will refer to a local variable outside?
class C
end
var = "I am a local var outside"
C.class_eval do
def self.a_class_method
puts var
end
end
I know, this is not correct, because the def created a new scope.
I also know that ...
36
votes
5
answers
14k
views
What can a const member function change? [duplicate]
C++ methods allow a const qualifier to indicate that the object is not changed by the member function. But what does that mean? Eg. if the instance variables are pointers, does it mean that the ...
36
votes
3
answers
14k
views
Swift Declare Class Func in Protocol
I had following confusion. As far as I know the main difference between static and class keywords when declaring method is that the second one could be overridden in subclasses.
The problem
However ...
35
votes
4
answers
22k
views
How do I list all objects created from a class in Ruby? [duplicate]
Is there any way in Ruby for a class to know how many instances of it exist and can it list them?
Here is a sample class:
class Project
attr_accessor :name, :tasks
def initialize(options)
@...
33
votes
5
answers
38k
views
Static classes in Python
I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class.
I'm writing a program in Python. Is it a bad style, if ...
33
votes
3
answers
3k
views
Why use classmethod instead of staticmethod? [duplicate]
I know what they do and I've seen many examples of both, but I haven't found a single example where I would have to use classmethod instead of replacing it with a staticmethod.
The most common ...
32
votes
6
answers
14k
views
Same name for classmethod and instancemethod
I'd like to do something like this:
class X:
@classmethod
def id(cls):
return cls.__name__
def id(self):
return self.__class__.__name__
And now call id() for either the ...
32
votes
5
answers
22k
views
What's the difference between "class method" and "static method"?
I've worked with a few different languages such as Java, C#, and Objective-C.
In most languages, methods that don't require an instance of an object are called static methods. However, when it comes ...
31
votes
1
answer
26k
views
Factory method for objects - best practice?
This is a question regarding the best practice for creating an instance of a class or type from different forms of the same data using python. Is it better to use a class method or is it better to use ...
30
votes
2
answers
23k
views
Why always add self as first argument to class methods? [duplicate]
Possible Duplicate:
Why do you need explicitly have the “self” argument into a Python method?
I understand why self is always the first argument for class methods, this makes total sense, but if ...
30
votes
1
answer
6k
views
Rails –Testing named scopes: test scope results or scope configuration?
How should Rails named scopes be tested? Do you test the results returned from a scope, or that your query is configured correctly?
If I have a User class with an .admins method like:
class User &...
28
votes
4
answers
36k
views
Cannot call a class method with [self theMethod:]
I am trying to write a class method in Objective C. The project builds fine when I declare the method. But the build fails whenever I try to call the method. Here is my code.
Header File
#import <...
28
votes
2
answers
6k
views
What is the difference between class method vs. class field function vs. class field arrow function?
What is the difference between class method, class property which is a function, and class property which is an arrow function? Does the this keyword behave differently in the different variants of ...
28
votes
2
answers
39k
views
Can a python @classmethod be inherited?
For example, I have a base class and a derived class:
>>> class Base:
... @classmethod
... def myClassMethod(klass):
... pass
...
>>> class Derived:
... pass
...
>>&...
27
votes
4
answers
27k
views
Call a class method from within that class
Is there a way to call a class method from another method within the same class?
For example:
+classMethodA{
}
+classMethodB{
//I would like to call classMethodA here
}
27
votes
1
answer
9k
views
super and __new__ confusion
As what I just learned, I can use super() this way:
super(class, obj_of_class-or-_subclass_of_class)
Code goes below:
#Case 1
class A(object):
def __init__(self):
print "A init"
class B(...
25
votes
1
answer
29k
views
Calling class methods via class name vs self
Suppose we have a class named Calculator. There's a class method in it, called runProgram.
If I wanted to call this class method, inside the class's implementation, what would the difference between ...
25
votes
6
answers
36k
views
Various errors in code that tries to call classmethods [closed]
I have this code:
class SomeClass:
@classmethod
def func1(cls,arg1):
#---Do Something---
@classmethod
def func2(cls,arg1):
#---Do Something---
# A 'function map' ...
25
votes
2
answers
2k
views
Why is @staticmethod not preserved across classes, when @classmethod is?
Take the following example script:
class A(object):
@classmethod
def one(cls):
print("I am class")
@staticmethod
def two():
print("I am static")
class B(object):
...
24
votes
4
answers
23k
views
What does 'self' refer to in a @classmethod?
I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being ...
24
votes
4
answers
27k
views
Override method with different argument types in extended class - Typescript
I want to override a method and pass different argument types to it:
class Base {
public myMethod(myString: string): undefined {
return;
}
}
class Child extends Base {
public ...
22
votes
2
answers
9k
views
why __getitem__ cannot be classmethod?
Suppose following class:
class Class(object):
@classmethod
def getitem(*args):
print 'getitem %s' % (args,)
@classmethod
def __getitem__(*args):
print '__getitem__ %s' ...
22
votes
2
answers
12k
views
Python - can I programmatically decorate class methods from a class instance?
I have an object hierarchy in which almost all of the methods are class methods. It looks like the following:
class ParentObject(object):
def __init__(self):
pass
@classmethod
...
20
votes
5
answers
13k
views
Check if a function uses @classmethod
TL;DR How do I find out whether a function was defined using @classmethod or something with the same effect?
My problem
For implementing a class decorator I would like to check if a method takes the ...
20
votes
4
answers
11k
views
Class methods which create new instances
Apart from the standard [[MyClass alloc] init] pattern, some objects are built from static methods like MyClass *obj = [MyClass classWithString:@"blabla"]
According to widespread memory management ...
18
votes
4
answers
13k
views
In Ruby, inside a class method, is self the class or an instance?
I know that self is the instance inside of an instance method. So, then, is self the class inside of a class method? E.g., Will the following work in Rails?
class Post < ActiveRecord::Base
def ...
18
votes
8
answers
20k
views
Is there a way to call a private Class method from an instance in Ruby?
Other than self.class.send :method, args..., of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.
UPDATE:
@Jonathan ...
18
votes
1
answer
8k
views
How to call a parent class's @classmethod from an overridden @classmethod in Python?
Let's say I have a class
class SimpleGenerator(object):
@classmethod
def get_description(cls):
return cls.name
class AdvancedGenerator(SimpleGenerator):
@classmethod
def ...
18
votes
4
answers
2k
views
What are the differences between a `classmethod` and a metaclass method?
In Python, I can create a class method using the @classmethod decorator:
>>> class C:
... @classmethod
... def f(cls):
... print(f'f called with cls={cls}')
...
>>&...
17
votes
3
answers
25k
views
Ruby: Can I use instance methods inside a class method?
I have a class that contains this class method:
def self.get_event_record(row, participant)
event = Event.where(
:participant_id => participant.id,
:event_type_code => row[:...
17
votes
1
answer
12k
views
what is the use and when to use @classmethod in python? [duplicate]
I have never used @classmethod and I do not think of any examples to use it, I know how it works but I do not know when it's time to use it for example
class Example:
def __init__(self,param1,...