Jump to content
Korean Random
DIVlNATOR

Изменение окна канала (Кланчат)

Recommended Posts

Добрый день товарищи...
Python до этого не изучал, многое что не особо понятно после Java.

Немного не пойму строчку из мода "mod_versus":

old_getFullName = BWChannelEntity.getFullName

1) почему BWChannelEntyty - это статичный класс?
2) почему "getFullName" укзана как переменная, а не метод?

3) а. Если выполнить из PJOrion, то в первом случае исключение:

*** NameError: name 'BWChannelEntity' is not defined
***
*** <unbound method BWChannelEntity.getFullName>

 б. А если выполнить как BWChannelEntity.getFullName() то:
 

*** TypeError: unbound method getFullName() must be called with BWChannelEntity instance as first argument (got nothing instead)


4) Я наверно не совсем понимаю как получить обьявленный ранее обьект и изменить его...

 

В конечном итоге, я хочу получить: Найти окно клан-чата, и переименовать его
 

Share this post


Link to post

Short link
Share on other sites

Ищите дальше, а способ что вы написали можете забыть, он не верный

Edited by Ekspoint
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

@Ekspoint Спасибо...

Еще вот так пробовал, но там нету сеттера:
 

from messenger.storage import storage_getter, ChannelsStorage

class ClanChannelCriteria(object):
    def filter(self, channel):
        return channel.getName() == '[SPCTE]'

storage = storage_getter('channels')()

if isinstance(storage, ChannelsStorage):
    channel = storage.getChannelByCriteria(ClanChannelCriteria())
    
    print channel.getName()

 

Share this post


Link to post

Short link
Share on other sites

@Ekspoint 
Вроде разобрался... Но немного пока для меня это магия, что можно заменить метод инициализированного класса своим методом...

1410777323_.png.bff29f18e8b48a484414b26ebafe6af5.png

Edited by DIVlNATOR

Share this post


Link to post

Short link
Share on other sites
20.05.2020 в 15:22, DIVlNATOR сказал:

1) почему BWChannelEntyty - это статичный класс?

 

Тыц. Это обычный класс, а getFullName это функция. 

 

Можно переопределить функцию в классе на свою, но делать это нужно до того, как движок походу работы клиента воспользуется этим классом для создания рабочего экземпляра объекта. 

 

spacer.png

Edited by StranikS_Scan
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

@StranikS_Scan 
Спасибо. Я понял уже... Прочитал про getAttr и setAttr. Попутно просто Python изучаю. Я вот так еще обернул в декоратор:

# coding=utf-8

from gui.mods.autumn_core import AutumnEnum

# Декоратор для замены методов обьявленного класса
#
#   @Override(Class, 'method')
#   def test(self, *args)
#
class Override:
    __methodType = None
    __methodName = None
    __clazz = None

    MethodType = AutumnEnum(['FUNCTION', 'METHOD', 'STATICMETHOD'])

    @classmethod
    def __init__(cls, clazz, method_name, method_type=MethodType.FUNCTION):
        """
        :type clazz: type
        :type method_name: str
        :type method_type: MethodType
        :return None
        """
        cls.__clazz = clazz
        cls.__methodName = method_name
        cls.__methodType = method_type

    @classmethod
    def __call__(cls, *args, **kwargs):
        func = args[0]
        if type(func == 'function'):
            
            if cls.__methodType == Override.MethodType.METHOD:
                cls.__overrideMethod(func)
            elif cls.__methodType == Override.MethodType.STATICMETHOD:
                cls.__overrideStaticMethod(func)
            else:
                cls.__overrideMethod(func)

    @classmethod
    def __override(cls, new_method):
        if hasattr(cls.__clazz, cls.__methodName):
            if isinstance(getattr(cls.__clazz, cls.__methodName), property):
                setattr(cls.__clazz, cls.__methodName, property(new_method))
            else:
                setattr(cls.__clazz, cls.__methodName, new_method)

    @classmethod
    def __overrideStaticMethod(cls, new_method):
        cls.__override(staticmethod(new_method))

    @classmethod
    def __overrideMethod(cls, new_method):
        cls.__override(classmethod(new_method))


class Test(object):

    def test(self):
        return 1234


print Test.test()


@Override(clazz=Test, method_name='test')
def test2():
    return 555

print Test.test()

 

Share this post


Link to post

Short link
Share on other sites
23.05.2020 в 13:47, DIVlNATOR сказал:

@StranikS_Scan 
Спасибо. Я понял уже... Прочитал про getAttr и setAttr. Попутно просто Python изучаю. Я вот так еще обернул в декоратор:


# coding=utf-8

from gui.mods.autumn_core import AutumnEnum

# Декоратор для замены методов обьявленного класса
#
#   @Override(Class, 'method')
#   def test(self, *args)
#
class Override:
    __methodType = None
    __methodName = None
    __clazz = None

    MethodType = AutumnEnum(['FUNCTION', 'METHOD', 'STATICMETHOD'])

    @classmethod
    def __init__(cls, clazz, method_name, method_type=MethodType.FUNCTION):
        """
        :type clazz: type
        :type method_name: str
        :type method_type: MethodType
        :return None
        """
        cls.__clazz = clazz
        cls.__methodName = method_name
        cls.__methodType = method_type

    @classmethod
    def __call__(cls, *args, **kwargs):
        func = args[0]
        if type(func == 'function'):
            
            if cls.__methodType == Override.MethodType.METHOD:
                cls.__overrideMethod(func)
            elif cls.__methodType == Override.MethodType.STATICMETHOD:
                cls.__overrideStaticMethod(func)
            else:
                cls.__overrideMethod(func)

    @classmethod
    def __override(cls, new_method):
        if hasattr(cls.__clazz, cls.__methodName):
            if isinstance(getattr(cls.__clazz, cls.__methodName), property):
                setattr(cls.__clazz, cls.__methodName, property(new_method))
            else:
                setattr(cls.__clazz, cls.__methodName, new_method)

    @classmethod
    def __overrideStaticMethod(cls, new_method):
        cls.__override(staticmethod(new_method))

    @classmethod
    def __overrideMethod(cls, new_method):
        cls.__override(classmethod(new_method))


class Test(object):

    def test(self):
        return 1234


print Test.test()


@Override(clazz=Test, method_name='test')
def test2():
    return 555

print Test.test()

 

декораторы можно взять у хвм и городить ничего не нужно)

  • Upvote 2

Share this post


Link to post

Short link
Share on other sites

@Ekspoint Спасибо.. Да недавно натолкнулся в исходниках night_dragon_on...

Единственное я не понял как работать с кодировкой... В Orione данный фокус норм отрабатывал:

string = 'Привет всем!'.decode('cp1251')
string.encode("utf-8")

После компиляции в названии окошка в боевом клиенте надпись типа "Ppp". В шапке файла стоит указание на кодировку файла...

# -*- coding: utf-8 -*-

Причем в клан чат пишется все по русски.

Не знаю... Может смотрю в сторону того, что нужно найти как подгружаются файлы *.mo. Добавить свой файлик и из него уже забирать фразы.. Но думаю, что есть способ легче)))

Edited by DIVlNATOR

Share this post


Link to post

Short link
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...