class-attribute

Class attributes in Python

允我心安 提交于 2019-12-13 06:53:04
问题 Is there any difference in the following two pieces of code? If not, is one preferred over the other? Why would we be allowed to create class attributes dynamically? Snippet 1 class Test(object): def setClassAttribute(self): Test.classAttribute = "Class Attribute" Test().setClassAttribute() Snippet 2 class Test(object): classAttribute = "Class Attribute" Test() 回答1: It's more natural to do it like #2, but notice that they do different things. With #2, the class always has the attribute. With

Kotlin: Initialize class attribute in constructor

情到浓时终转凉″ 提交于 2019-12-12 07:42:25
问题 I create a Kotlin-class with a class attribute, which I want to initialize in the constructor: public class TestClass { private var context : Context? = null // Nullable attribute public constructor(context : Context) { this.context = context } public fun doSomeVoodoo() { val text : String = context!!.getString(R.string.abc_action_bar_home_description) } } Unfortunately I have to declare the attribute as Nullable with the "?" sign, although the attribute will be initialized in the constructor

Kotlin: Initialize class attribute in constructor

依然范特西╮ 提交于 2019-12-03 10:21:23
I create a Kotlin-class with a class attribute, which I want to initialize in the constructor: public class TestClass { private var context : Context? = null // Nullable attribute public constructor(context : Context) { this.context = context } public fun doSomeVoodoo() { val text : String = context!!.getString(R.string.abc_action_bar_home_description) } } Unfortunately I have to declare the attribute as Nullable with the "?" sign, although the attribute will be initialized in the constructor. Declaring this attribute as Nullable-attribute makes it always necessary to force an NonNull-value