标签: class-method

在Python中访问实例的名称以进行打印

因此,作为"像计算机科学家一样思考"问题17.6的一部分,我写了一个名为袋鼠的课程:

class Kangaroo(object):

    def __init__(self, pouch_contents = []):
        self.pouch_contents = pouch_contents

    def __str__(self):
        '''
        >>> kanga = Kangaroo()
        >>> kanga.put_in_pouch('olfactory')
        >>> kanga.put_in_pouch(7)
        >>> kanga.put_in_pouch(8)
        >>> kanga.put_in_pouch(9)
        >>> print kanga
        "In kanga's pouch there is: ['olfactory', 7, 8, 9]"
        '''

        return "In %s's pouch there is: %s" % (object.__str__(self), self.pouch_contents)

    def put_in_pouch(self, other):
        '''
        >>> kanga = Kangaroo()
        >>> kanga.put_in_pouch('olfactory')
        >>> kanga.put_in_pouch(7)
        >>> kanga.put_in_pouch(8)
        >>> kanga.put_in_pouch(9)
        >>> kanga.pouch_contents
        ['olfactory', 7, 8, 9]
        '''

        self.pouch_contents.append(other)
Run Code Online (Sandbox Code Playgroud)

让我疯狂的是,我希望能够编写一个字符串方法,通过__str__书面下面的单元测试.我现在得到的是:

In <__main__.Kangaroo object at …
Run Code Online (Sandbox Code Playgroud)

python printing string class-method

2
推荐指数
1
解决办法
265
查看次数

C++ ::使用向量迭代器调用类方法?

我有一个名为Room的类,Room类有setPrice和display函数.

我将房间对象存储在矢量中:

room.push_back(Room("r001", 1004, 2, "small"));
room.push_back(Room("r002", 1005, 2, "small"));
room.push_back(Room("r003", 2001, 4, "small"));
room.push_back(Room("r004", 2002, 4, "small"));
Run Code Online (Sandbox Code Playgroud)

在我的主要功能中,我创建了一个显示所有房间的显示功能.这是我的代码:

void displayRoom()
{
    vector<Room>::iterator it;
    for (it = room.begin(); it != room.end(); ++it) {
         *it.display(); // just trying my luck to see if it works
    }
}
Run Code Online (Sandbox Code Playgroud)

但它没有调用Room的显示方法.

如何调用Room(类)的显示方法(无参数)和setPrice(1参数)方法?

c++ vector class-method

2
推荐指数
1
解决办法
2万
查看次数

如何在python中引用重写类函数

我知道C++和Java,我不熟悉Pythonic编程.所以也许这是我想要做的坏风格.

考虑下面的例子:

class foo:
        def a():
                __class__.b() # gives: this is foo
                bar.b() # gives: this is bar
                foo.b() # gives: this is foo
                # b() I'd like to get "this is bar" automatically

        def b():
                print("this is foo")

class bar( foo ):
        def b( ):
                print("this is bar")

bar.a()
Run Code Online (Sandbox Code Playgroud)

请注意,我没有使用self参数,因为我没有尝试创建类的实例,因为不需要我的任务.我只是试图以一种可以覆盖函数的方式引用函数.

python oop inheritance class-method static-functions

2
推荐指数
1
解决办法
75
查看次数

Java类没有main方法

我需要为GCD运行一个方法代码.我的java文件名为"GCD.java",公共类称为"GCD".然而,我仍然收到消息"GCD类没有主要方法",即使我的任何一行都没有红色的解释点圈.我可以在没有方法代码的情况下运行代码(即public static void main(String [] args)),但我需要使用方法运行代码.谢谢.

==========================

import java.util.Scanner;

    public class GCD
    {

        public static int getDivisor(int x, int y)
        {


        System.out.println("Greatest Common Divisor Finder");
        System.out.println();

        String choice = "y";
        Scanner sc = new Scanner(System.in);
        while (choice.equalsIgnoreCase("y"))
        {

            System.out.print("Enter first number: ");
            x = sc.nextInt();
            System.out.print("Enter second number: ");
            y = sc.nextInt();

            int secondNumber = 0;
            int firstNumber = 0;
            int Greatestcommondivisionfinder = 0;

            // x = first,  y = second
            if (x > y)
                {
                    do
        {
                        x -= …
Run Code Online (Sandbox Code Playgroud)

java class-method

2
推荐指数
1
解决办法
1万
查看次数

Swift:为什么类方法有返回类型AnyObject?

NSDate.distantFuture()记录为返回类型的对象NSDate.

那么,为什么它有一个返回类型AnyObject,而不是NSDate

initialization return-type nsdate class-method swift

2
推荐指数
1
解决办法
922
查看次数

Ruby 从实例方法调用类方法

从实例方法调用类方法的语法是什么?假设我有以下内容

class Class1
    def initialize
       #instance method
       self.class.edit
       puts "hello"
    end

    def self.edit
       #class method
       "ha"
    end
end

c= Class1
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我没有得到任何输出。

ruby methods class-method instance-methods

2
推荐指数
1
解决办法
2670
查看次数

Python __call __()这是一个隐式的类方法吗?

我想在python中实现一个单例模式,我喜欢http://www.python-course.eu/python3_metaclasses.php中描述的模式.

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=Singleton):
    pass
class RegularClass():
    pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y) 
Run Code Online (Sandbox Code Playgroud)

代码工作得很完美.但是,__call__()没有self,它也没有@classmethod@staticmethod声明.

但是,在Python数据模型https://docs.python.org/3/reference/datamodel.html#object.__call__中,__call__()方法在参数中有一个self.

如果我通过self或声明为@staticmethod或,则代码不起作用@classmethod.

有人可以解释一下该__call__()方法背后的语法逻辑.

python metaclass class-method python-3.x

2
推荐指数
1
解决办法
1652
查看次数

在TypeScript中获取intance的类

如何在TypeScript中获取实例的类?这个问题类似于在运行时在TypeScript中获取对象的类名,但我不想获取类名.我想要上课.

我需要这个吗?TypeScript没有类方法,只有静态方法.但它们不是虚拟的.为了将我的心智模型完全转换为Js代码,我需要有虚拟类方法.

我的想法是做这样的事情:

function classOf<T>(o: T) : any {
    return o.class; // How to write this???
}

class Foo {
    static tryMe() : string {
        return "foo";
    }

}

class Bar extends Foo {
    static tryMe() : string {
        return "bar";
    }

}

function testPolymorphClassMethod(instance : Foo) {
    console.log(classOf(instance).tryMe());
}

testPolymorphClassMethod(new Foo()); // Should print "foo"
testPolymorphClassMethod(new Bar()); // Should print "bar"
Run Code Online (Sandbox Code Playgroud)

只要具体类可用,我就可以直接调用它的静态方法.如果只有一个实例可用,我想调用它的类的静态方法,例如手动虚拟.

问题是我不知道如何编写classOf函数.它可能根本不可能.

我也在尝试这个:

function classOf<T>(o: T) : typeof T {
    return typeof o;
}
Run Code Online (Sandbox Code Playgroud)

但它给出了一个comiple错误:

"T仅指类型,但在此处用作值". …

class-method typescript

2
推荐指数
1
解决办法
1904
查看次数

使用 self 与 cls 访问单元测试中的变量

假设我有一个简单的类对象,看起来像某种Counter(当然它还有其他功能,但超出了这个问题的范围):

from collections import Counter

class Vocabulary:
    def __init__(self, words):
        self.vocab = Counter(words)
Run Code Online (Sandbox Code Playgroud)

并将Vocabulary类添加到单元测试中,我可以setUpClass这样使用类方法:

import unittest

class VocabularyTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.vocab = Vocabulary(["z", "a", "b", "c", "f", "d", "e", "g", "a", "d", "b", "e", "w"])


    def test_counts_set_correctly(self):
        self.assertEqual(cls.vocab["a"], 2)
Run Code Online (Sandbox Code Playgroud)

或者我可以只使用self

class VocabularyTests(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(VocabularyTests, self).__init__(*args, **kwargs)
        self.vocab = Vocabulary(["z", "a", "b", "c", "f", "d", "e", "g", "a", "d", "b", "e", "w"])

    def test_counts_set_correctly(self):
        self.assertEqual(self.vocab["a"], 2)
Run Code Online (Sandbox Code Playgroud)

以上两者都可以正常工作。但是如果我有一种非Pythonic 模式怎么办:

import …
Run Code Online (Sandbox Code Playgroud)

python unit-testing self class-method

2
推荐指数
1
解决办法
2742
查看次数

弃用 Rails 中所有类方法的最佳方法

我有一个ActiveRecord具有多个类方法的类(它不是模型)。必须弃用所有类方法。做到这一点的最佳方法是什么?

class MyClass
  class << self
    def method_to_deprecate_1
      ...
    end
    ...
    def method_to_deprecate_100
      ...
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails deprecated class-method deprecation-warning

2
推荐指数
1
解决办法
154
查看次数