Skip to main content

Questions tagged [class-method]

Methods that are called on a class instead of on an object.

Filter by
Sorted by
Tagged with
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?
Daryl Spitzer's user avatar
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 ...
user avatar
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?
Devoted's user avatar
  • 181k
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. ...
Peter's user avatar
  • 131k
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 ...
David Webb's user avatar
  • 193k
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): ...
deft_code's user avatar
  • 58.5k
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 ...
marue's user avatar
  • 5,676
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!' ...
Sridhar Ratnakumar's user avatar
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 ...
Chinasaur's user avatar
  • 2,138
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/...
dza's user avatar
  • 1,494
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. ...
coffee-grinder's user avatar
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 ...
dkubb's user avatar
  • 2,126
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 ...
Tuxdude's user avatar
  • 48.9k
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 ...
dochead's user avatar
  • 1,825
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’ ...
pez_dispenser's user avatar
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 ...
brad's user avatar
  • 32.2k
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 ...
Josh Gibson's user avatar
  • 22.6k
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 ...
scottm's user avatar
  • 28.2k
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....
tadasajon's user avatar
  • 14.7k
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 ...
Croplio's user avatar
  • 3,523
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 ...
Daniel's user avatar
  • 934
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 ...
hris.to's user avatar
  • 6,333
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) @...
Amit Erandole's user avatar
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 ...
rynd's user avatar
  • 1,875
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 ...
Patrik Lippojoki's user avatar
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 ...
Markus Meskanen's user avatar
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 ...
aryaxt's user avatar
  • 77.2k
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 ...
Yani's user avatar
  • 1,505
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 ...
jonathan topf's user avatar
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 &...
Paul Fioravanti's user avatar
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 <...
Stefan Bossbaly's user avatar
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 ...
Combine's user avatar
  • 4,074
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 ... >>&...
yuklai's user avatar
  • 1,645
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 }
prostock's user avatar
  • 9,467
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(...
Alcott's user avatar
  • 18.4k
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 ...
Milad's user avatar
  • 1,269
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' ...
user1126425's user avatar
  • 2,525
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): ...
Alex Forbes's user avatar
  • 3,339
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 ...
Yes - that Jake.'s user avatar
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 ...
A_A's user avatar
  • 1,872
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' ...
QwiglyDee's user avatar
  • 798
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 ...
tadasajon's user avatar
  • 14.7k
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 ...
hlt's user avatar
  • 6,267
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 ...
pistacchio's user avatar
  • 58.3k
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 ...
ma11hew28's user avatar
  • 125k
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 ...
James A. Rosen's user avatar
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 ...
Krystian Cybulski's user avatar
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}') ... >>&...
user200783's user avatar
  • 14.1k
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[:...
steve_gallagher's user avatar
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,...
Francisco's user avatar
  • 561

1
2 3 4 5
19